jQuery.validate use of essential

jQuery.validate is a very good form validation tools, simple approachable, and experience to achieve good results, although long used in the project, but seeing this article well written is good, reproduced under to share with you.

One must use the official website of the former: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
API: http://jquery.bassistance.de/api-browser/plugins.html
Current Version: 1.5.5
Need JQuery version: 1.2.6 +, Compatibility 1.3.2
<script src="../js/jquery.js" type="text/javascript"> </ script>
<script src="../js/jquery.validate.js" type="text/javascript"> </ script>

Second, the default validation rules
(1) required: true losing field
(2) remote: "check.php" using ajax method call check.php validate input values
(3) email: true must enter the correct e-mail format
(4) url: true must enter the correct URL format
(5) date: true must enter the correct date format
(6) dateISO: true must enter the correct date format (ISO), for example :2009-06-23, 1998/01/22 verification only format, do not verify the validity of
(7) number: true must enter a valid number (negative numbers, decimals)
(8) digits: true must enter an integer
(9) creditcard: must enter a valid credit card number
(10) equalTo: "# field" and the # field enter the value must be the same
(11) accept: Enter a valid extension of the string (upload the file extension)
(12) maxlength: 5 Enter the length of at most 5 string (character count as one character)
(13) minlength: 10 Enter the minimum length is 10 character string (character count as one character)
(14) rangelength: [5,10] must be between the input length of the string between 5 and 10 ") (character count as one character)
(15) range: [5,10] between the input value must be between 5 and 10
(16) max: 5 input value is not greater than 5
(17) min: 10 input value is not less than 10

Third, the default prompt
messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein g eyebrow ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $. validator.format ("Please enter no more than {0} characters."),
minlength: $. validator.format ("Please enter at least {0} characters."),
rangelength: $. validator.format ("Please enter a value between {0} and {1} characters long."),
range: $. validator.format ("Please enter a value between {0} and {1 }."),
max: $. validator.format ("Please enter a value less than or equal to {0 }."),
min: $. validator.format ("Please enter a value greater than or equal to {0}.")
}
If you need to modify, add in the js code:
jQuery.extend (jQuery.validator.messages, {
required: "Required field",
remote: "Please correct the field,"
email: "Please enter a valid e-mail format"
url: "Please enter a valid URL"
date: "Please enter a valid date"
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a valid number",
digits: "can only enter integer"
creditcard: "Please enter a valid credit card number,"
equalTo: "Please re-enter the same value"
accept: "Please enter a valid string extension"
maxlength: jQuery.validator.format ("Please enter a maximum length of the string is {0}")
minlength: jQuery.validator.format ("Please enter a minimum length of the string is {0}")
rangelength: jQuery.validator.format ("Please enter a length of between {0} and {1} string")
range: jQuery.validator.format ("Please enter a number between {0} and {1} value"),
max: jQuery.validator.format ("Please enter a maximum value of {0}")
min: jQuery.validator.format ("Please enter a minimum value of {0}")
});
Recommended practices, this file into messages_cn.js, in the introduction page
<script src="../js/messages_cn.js" type="text/javascript"> </ script>

Fourth, use
1. Will check write control rules
<script src="../js/jquery.js" type="text/javascript"> </ script>
<script src="../js/jquery.validate.js" type="text/javascript"> </ script>
<script src="./js/jquery.metadata.js" type="text/javascript"> </ script>
$ (). Ready (function () {
$ ("# SignupForm"). Validate ();
});

<form method="get" action="">
<p>
<label for="firstname"> Firstname </ label>
<input name="firstname" />
</ P>
<p>
<label for="email"> E-Mail </ label>
<input name="email" />
</ P>
<p>
<label for="password"> Password </ label>
<input name="password" type="password" />
</ P>
<p>
<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />
</ P>
<p>
<input type="submit" value="Submit"/>
</ P>
</ Form>
Use class ="{}" way, they must bring bag: jquery.metadata.js
You can use the following method, modify the prompts:
class = "{required: true, minlength: 5, messages: {required: 'Please enter content'}}"
EqualTo keywords using the back of the content must be in quotes, the following code:
class = "{required: true, minlength: 5, equalTo: '# password'}"
Another way of using keywords: meta (meta-data to use other plug-ins you want to wrap your validation rules in their own projects can use this special option)
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
For example:
meta: "validate"
<input name="password" type="password" />

Another way:
$. Metadata.setType ("attr", "validate");
This can validate = "{required: true}" way, or class = "required", but the class = "{required: true, minlength: 5}" will not work

2. To write the code validation rules

$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
rules: {
firstname: "required",
email: {
required: true,
email: true
}
password: {
required: true,
minlength: 5
}
confirm_password: {
required: true,
minlength: 5,
equalTo: "# password"
}
}
messages: {
firstname: "Please enter your name"
email: {
required: "Please enter the Email address",
email: "Please enter a valid email address"
}
password: {
required: "Please enter your password"
minlength: jQuery.format ("password can not be less than {0} characters")
}
confirm_password: {
required: "Please enter the confirmation code"
minlength: "Confirm password can not be less than 5 characters"
equalTo: "Enter the password twice inconsistent inconsistent"
}
}
});
});
/ / Messages at, if not a control message, will call the default message

<form method="get" action="">
<p>
<label for="firstname"> Firstname </ label>
<input name="firstname" />
</ P>
<p>
<label for="email"> E-Mail </ label>
<input name="email" />
</ P>
<p>
<label for="password"> Password </ label>
<input name="password" type="password" />
</ P>
<p>
<label for="confirm_password"> Confirm Password </ label>
<input name="confirm_password" type="password" />
</ P>
<p>
<input type="submit" value="Submit"/>
</ P>
</ Form>
required: true must have a value
required: "# aa: checked" expression is true, then the need to verify
required: function () {} return true, the table behind the need to verify that the two commonly used, the form needs to fill or not fill both elements

Five commonly used methods and attention problems
1. By other means instead of the default SUBMIT
$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
submitHandler: function (form) {
alert ("submitted");
form.submit ();
}
});
});
Validate the default values can be set, written as follows:
$. Validator.setDefaults ({
submitHandler: function (form) {alert ("submitted!"); form.submit ();}
});
If you want to submit the form, you need form.submit () instead of $ (form). Submit ()

2.debug, if this parameter is true, then the form will not submit, just to check, very convenient for debugging
$ (). Ready (function () {
$ ("# SignupForm"). Validate ({
debug: true
});
});
If a page has multiple forms, with
$. Validator.setDefaults ({
debug: true
})

3.ignore: ignore some elements do not validate
ignore: ". ignore"

4.errorPlacement: Callback Default: the error message on the authentication element placed behind the specified error, default is: error.appendTo (element.parent ()); that the wrong information on the verification of the elements behind
errorPlacement: function (error, element) {
error.appendTo (element.parent ());
}
/ / Example:
<tr>
<td> <label for="firstname"> First Name </ label> </ td>
<td> <input name="firstname" type="text" value="" maxlength="100" /> </ td>
<td> </ td>
</ Tr>
<tr>
<td>
<input name="dateformat" type="radio" value="0" />
<label for="dateformat_eu"> 14/02/07 </ label>
</ Td>
<td>
<input name="dateformat" type="radio" value="1" />
<label for="dateformat_am"> 02/14/07 </ label>
</ Td>
<td> </ td>
</ Tr>
<tr>
<td> </ td>
<td colspan="2">
<div>
<input type="checkbox" name="terms" />
<label for="terms"> I have read and accept the Terms of Use. </ label>
</ Div>
</ Td>
</ Tr>
errorPlacement: function (error, element) {
if (element.is (": radio"))
error.appendTo (element.parent (). next (). next ());
else if (element.is (": checkbox"))
error.appendTo (element.next ());
else
error.appendTo (element.parent (). next ());
}
The role of the code is: Under normal circumstances the error message displayed in the <td> </ td>, if a radio show in <td> </ td>, if the content is displayed on the back of checkbox
errorClass: String Default: "error"
Specify the css error class name, you can customize the style error
errorElement: String Default: "label"
What is wrong with the tag, the default is the label you can change em
errorContainer: Selector
Show or hide authentication information, you can automatically have an error message appears when the container property into a show that no errors hidden usefulness
errorContainer: "# messageBox1, # messageBox2"
errorLabelContainer: Selector
The wrong information to be consolidated in a container inside.
wrapper: String
What label on top of the errorELement then wrapped up the three properties generally be used simultaneously to achieve in a container display all error functions, and are hidden when there is no information
errorContainer: "div.error",
errorLabelContainer: $ ("# signupForm div.error"),
wrapper: "li"

Set the error style, can increase the icon
input.error {border: 1px solid red;}
label.error {
background: url (". / demo / images / unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
padding-bottom: 2px;
font-weight: bold;
color: # EA5200;
}
label.checked {
background: url (". / demo / images / checked.gif") no-repeat 0px 0px;
}
success: String, Callback
To verify that the elements of the action is validated, if followed by a string, will be treated as a css class, but also with a function
success: function (label) {
/ / Set as text for IE
label.html (""). addClass ("checked");
/ / Label.addClass ("valid"). Text ("Ok!")
}
Add a "valid" to verify the elements defined in the CSS style <style> label.valid {} </ style>
success: "valid"

nsubmit: Boolean Default: true
Submission verification. CD set to false to verify with other methods
onfocusout: Boolean Default: true
Lost focus is to verify (not including checkboxes / radio buttons)
onkeyup: Boolean Default: true
When the keyup validation.
onclick: Boolean Default: true
Click the checkboxes and radio when the validation
focusInvalid: Boolean Default: true
After the form is submitted, not verified form (the first or get the focus before submitting the form is not validated) will be the focus
focusCleanup: Boolean Default: false
If it is true then when the element is not authenticated access to focus, to remove errors. Used together to prevent and focusInvalid

/ / Reset the form
$ (). Ready (function () {
var validator = $ ("# signupForm"). validate ({
submitHandler: function (form) {
alert ("submitted");
form.submit ();
}
});
$ ("# Reset"). Click (function () {
validator.resetForm ();
});
});

remote: URL
Way to use ajax validation, default values will be submitted to the current remote address verification, if required to submit any other value, you can use the data option
remote: "check-email.php"
remote: {
url: "check-email.php", / / background processing
type: "post", / / data transmission mode
dataType: "json", / / accept the data format
data: {/ / data to pass
username: function () {
return $ ("# username"). val ();
}
}
}

Remote address can only output "true" or "false", can not have other output

addMethod: name, method, message
Custom validation method

/ / Two bytes in the text
jQuery.validator.addMethod ("byteRangeLength", function (value, element, param) {
var length = value.length;
for (var i = 0; i <value.length; i + +) {
if (value.charCodeAt (i)> 127) {
length + +;
}
}
return this.optional (element) | | (length> = param [0] & & length <= param [1]);
}, $. Validator.format ("Please be sure to enter the value {0} - {1} bytes between (a Chinese character count 2 bytes )"));

/ / Postal Code authentication
jQuery.validator.addMethod ("isZipCode", function (value, element) {
var tel = / ^ [0-9] {6} $ /;
return this.optional (element) | | (tel.test (value));
}, "Please enter your zip code correctly");

radio and checkbox, select the authentication
The required radio said one must be selected
<input type="radio" value="m" name="gender" />
<input type="radio" value="f" name="gender"/>
The required checkbox that must be selected
<input type="checkbox" name="agree" />
must select the checkbox of the minlength that the minimum number, maxlength is the maximum number is selected, rangelength: [2,3] that the number of intervals selected
<input type="checkbox" value="email" name="spam[]" />
<input type="checkbox" value="phone" name="spam[]" />
<input type="checkbox" value="mail" name="spam[]" />

select the required selected value that can not be empty
<select name="jungle" title="Please select something!">
<option value=""> </ option>
<option value="1"> Buga </ option>
<option value="2"> Baga </ option>
<option value="3"> Oi </ option>
</ Select>
select the minlength that the minimum number of selected (multiple selection of the select), maxlength is the maximum number is selected, rangelength: [2,3] that the number of intervals selected
<select name="fruit" title="Please select at least two fruits" multiple="multiple">
<option value="b"> Banana </ option>
<option value="a"> Apple </ option>
<option value="p"> Peach </ option>
<option value="t"> Turtle </ option>
</ Select>

分类:Web 时间:2010-10-31 人气:188
分享到:
blog comments powered by Disqus

相关文章

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.622 (s). 12 q(s)