Introduction to the usage of jquery.validate

  • 2020-03-29 23:42:38
  • OfStack

Preparation work
Required JQuery version: 1.2.6+, compatible with 1.3.2

Website address: (link: http://jqueryvalidation.org/)

Two, default calibration rules
(1)required:true
(2)remote:"check. PHP "USES the ajax method to call check. PHP to verify the input value  
(3)email:true must enter the correct format of the email & send;
(4)url:true must be entered in the correct format of the url  
(5)date:true must be entered in the correct format of the date  
(6)dateISO:true must enter the correct format date (ISO), e.g., 2009-06-23, 1998/01/22
(7)number:true you must enter a valid number (negative number, decimal number)& PI;
(8)digits:true must be entered as an integer & digits;
(9)creditcard: a valid creditcard number & mastercard must be entered;
(10)equalTo:"#field" input value must be the same as #field  
(11)accept: enter a string with a legal suffix (the suffix of the uploaded file) & PI;
(12)maxlength:5 a string with a maximum length of 5 (Chinese character counts as one character)& PI;
Enter a string with a minimum length of 10 (Chinese character counts as a character)& PI;
(14)rangelength:[5,10] input length must be between 5 and 10 string ")(Chinese character is a character)& PI;
(15)range:[5,10] the input value must be between 5 and 10.
(16) Max :5 input value cannot be greater than 5& PI;
(17)min:10 input value shall not be less than 10& PI;

Three, 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 The 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, you can add:

jQuery.extend(jQuery.validator.messages, {  
required: " Will be optional field ",  
remote: " Please correct this field ",  
email: " Please enter the correct email format ",  
url: " Please enter a valid web address ",  
date: " Please enter a valid date ",  
dateISO: " Please enter a valid date  (ISO).",  
number: " Please enter a valid number ",  
digits: " You can only enter integers ",  
creditcard: " Please enter a valid credit card number ",  
equalTo: " Please enter the same value again ",  
accept: " Please enter a string with a valid suffix name ",  
maxlength: jQuery.validator.format(" Please enter a length of at most  {0}  The string "),  
minlength: jQuery.validator.format(" Please enter a length of at least  {0}  The string "),  
rangelength: jQuery.validator.format(" Please enter a length between  {0}  and  {1}  String between "),  
range: jQuery.validator.format(" Please enter an intermediate  {0}  and  {1}  Between the value of the "),  
max: jQuery.validator.format(" Please enter a maximum  {0}  The value of the "),  
min: jQuery.validator.format(" Please enter a minimum of  {0}  The value of the ")  
});

It is recommended that this file be placed in messages_cn.js and introduced on the page

Use method
1. Write the validation rule to the control


<mce:script src="../js/jquery.js" mce_src="js/jquery.js" type="text/javascript"></mce:script>  
<mce:script src="../js/jquery.validate.js" mce_src="js/jquery.validate.js" type="text/javascript"></mce:script>  
<mce:script src="./js/jquery.metadata.js" mce_src="js/jquery.metadata.js" type="text/javascript"></mce:script>  
<mce:script type="text/javascript"><!--
$().ready(function() {  
$("#signupForm").validate();  
});
// --></mce:script>  
<form id="signupForm" method="get" action="">  
<p>  
<label for="firstname">Firstname</label>  
<input id="firstname" name="firstname" class="required" />  
</p>  
<p>  
<label for="email">E-Mail</label>  
<input id="email" name="email" class="required email" />  
</p>  
<p>  
<label for="password">Password</label>  
<input id="password" name="password" type="password" class="{required:true,minlength:5}" />  
</p>  
<p>  
<label for="confirm_password"> Confirm password </label>  
<input id="confirm_password" name="confirm_password" type="password" class="{required:true,minlength:5,equalTo:'#password'}" />  
</p>  
<p>  
<input class="submit" type="submit" value="Submit"/>  
</p>  
</form> 

To use the class="{}" method, you must introduce the package: jquery. Metadata. Js can modify the prompt by using the following method:
Class = "{required: true, minlength: 5, messages: {required: 'please enter the content'}}" when using equalTo keyword, later must be enclosed in quotation marks, the following code:
Class = "{required: true, minlength: 5, equalTo: '# password'}" another way, using the key words: meta (for metadata using other plugins you want to pack 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.
Such as:

meta: "validate" <input id="password" name="password" type="password" class="{validate:{required:true,minlength:5}}" /> 

There is another way:

$.metadata.setType("attr", "validate"); So you can use it validate="{required:true}" or class="required" , but class="{required:true,minlength:5}" Will not work  2. Write validation rules to code   
$().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 name ",  
email: {  
required: " Please enter the Email address ",  
email: " Please enter the correct one email address "  
},  
password: {  
required: " Please enter your password ",  
minlength: jQuery.format(" Password must not be less than {0} A character ")  
},  
confirm_password: {  
required: " Please enter a confirmation password ",  
minlength: " Make sure the password is no less than 5 A character ",  
equalTo: " The two input passwords are inconsistent and inconsistent "  
}  
}  
});  
});//Messages, if a control does not have a message, the default message is invoked


<form id="signupForm" method="get" action="">  
<p>  
<label for="firstname">Firstname</label>  
<input id="firstname" name="firstname" />  
</p>  
<p>  
<label for="email">E-Mail</label>  
<input id="email" name="email" />  
</p>  
<p>  
<label for="password">Password</label>  
<input id="password" name="password" type="password" />  
</p>  
<p>  
<label for="confirm_password"> Confirm password </label>  
<input id="confirm_password" name="confirm_password" type="password" />  
</p>  
<p>  
<input class="submit" type="submit" value="Submit"/>  
</p>  
</form>  

Required :true must have a value
Required: if the value of the "#aa:checked" expression is true, then validation is required
Required :function(){} returns true, table validation is required
The latter two are commonly used for elements in forms that need to be filled in or not filled in at the same time

Common methods and attention to problems

1. SUBMIT$(). Ready (function() {
$(" # signupForm "). The validate ({
SubmitHandler: function (form) {
Alert (" submitted ");
The form submit ();
}
});
});

You can set the default value of validate as follows:
$. The validator. SetDefaults ({
SubmitHandler: function (form) {alert (" submitted!" ); The form submit (); }
});

If you want to submit a form, use form.submit() instead of $(form).submit()

2. Debug, if this parameter is true, the form will not be submitted, only check, debugging is very convenient
$() ready (function () {
$(" # signupForm "). The validate ({
The debug: true,
});
});

If there are more than one form in a page, use
$. The validator. SetDefaults ({
The debug: true,
})

3. Ignore: ignore certain elements
Ignore: "ignore"

ErrorPlacement: Callback Default: puts the error message after the validated element

Specify where the error is placed, default: error.appendto (element.parent()); That is, the error message is placed after the validated element
ErrorPlacement: function (error, element) {
Error. AppendTo (element. The parent ());
} / / sample:


<tr>  
<td class="label"><label id="lfirstname" for="firstname">First Name</label></td>  
<td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>  
<td class="status"></td>  
</tr>  
<tr>  
<td style="padding-right: 5px;" mce_style="padding-right: 5px;">  
<input id="dateformat_eu" name="dateformat" type="radio" value="0" />  
<label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>  
</td>  
<td style="padding-left: 5px;" mce_style="padding-left: 5px;">  
<input id="dateformat_am" name="dateformat" type="radio" value="1"  />  
<label id="ldateformat_am" for="dateformat_am">02/14/07</label>  
</td>  
<td></td>  
</tr>  
<tr>  
<td class="label"> </td>  
<td class="field" colspan="2">  
<div id="termswrap">  
<input id="terms" type="checkbox" name="terms" />  
<label id="lterms" 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() );  
} 

ErrorClass: String Default: "error" : "error" : "errorClass: String Default: "error"

Specify the CSS class name for the error prompt. You can customize the style of the error prompt errorElement: String Default: "label"

What label is wrong? The default label is emerrorContainer: Selector

Show or hide the validation information, you can automatically achieve an error message when the container property into the display, no error when hidden, useful

ErrorContainer: "#messageBox1, #messageBox2"errorLabelContainer: Selector

Keep the error messages in one container. Wrapper: String

Generally, these three attributes are used at the same time to realize the function of displaying all error tips in a container, and automatically hide errorContainer when there is no information: "div.error",

ErrorLabelContainer: $(" # signupForm div. The error "),
Wrapper: "li" set the style of the error prompt, you can add the icon to display input.error {border: 1px solid red; }
Label. The error {
Background: url (". / demo/images/unchecked. GIF ") no - repeat 0 px 0 px; Padding - left: 16 px; Padding - bottom: 2 px; The font - weight: bold; Color: # EA5200;
}
Label. Checked {
Background: url (". / demo/images/checked the. GIF ") no - repeat 0 px 0 px;
} success: String, the Callback

The action after the element to be validated passes the validation, if with a string, will be treated as a CSS class, can also be with a function
Success: the function (label) {
/ / set    As the text for IE
Label. The HTML (" "). The addClass (" checked ");
/ / label. The addClass (" valid "). The text (" Ok!" )
}

Add "valid" to the validation element, the style defined in CSS
Success: "valid" nsubmit: Boolean Default: true

Verify on commit. Set only false to use other methods to verify
Onfocusout: Boolean Default: true

Losing focus is validation (excluding checkboxes/radio buttons)
Onkeyup: Boolean Default: true

Verify at keyup time.
Onclick: Boolean Default: true

Verify when checkboxes and radio are clicked
FocusInvalid: Boolean Default: true

After the form is submitted, the unvalidated form (the one that gets focus first or the one that gets focus before the submission) gets focus
FocusCleanup: Boolean Default: false

If true, remove the error when an element that fails validation gets focus. Avoid using // with focusInvalid to reset the form


$().ready(function() {  
var validator = $("#signupForm").validate({  
submitHandler:function(form){  
alert("submitted");  
form.submit();  
}   
});  
$("#reset").click(function() {  
validator.resetForm();  
});}); 

Using ajax for validation, the current validated value is submitted to the remote address by default, and if additional values need to be submitted, you can use the data option

remote: {  
url: "check-email.php", //Background handler & NBSP;
type: "post",   //Way of sending data & NBSP;
dataType: "json",   //Accept data format & NBSP;
data: { //The data to be passed
username: function() {  
return $("#username").val();  
}  
}  
}  

The remote address can only output "true" or "false", no other output addMethod: name, method, message
Custom validation methods

//Chinese character two bytes & NBSP;
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(" Make sure the input value is in {0}-{1} Between bytes ( One for Chinese characters 2 bytes )"));  
//Zip code verification & cake;
jQuery.validator.addMethod("isZipCode", function(value, element) {  
var tel = /^[0-9]{6}$/;  
return this.optional(element) || (tel.test(value));  
}, " Please fill in your zip code correctly ");  


radio and checkbox , select Validation of the radio the required Means that one must be selected   
<input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />  
<input  type="radio" id="gender_female" value="f" name="gender"/>checkbox the required Must be selected   
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />checkbox the minlength Represents the minimum number that must be selected ,maxlength Represents the maximum number of selections ,rangelength:[2,3] Represents the selected number of intervals   
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />  
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />  
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />  
select the required Represents selected value Can't be empty   
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">  
<option value=""></option>  
<option value="1">Buga</option>  
<option value="2">Baga</option>  
<option value="3">Oi</option>  
</select> 

The minlength of select represents the minimum number of selected items (multi-selection select), the maxlength represents the maximum number of selected items, and the range elength:[2,3] represents the range of selected items

radio and checkbox , select Validation of the radio the required Means that one must be selected   
<input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />  
<input  type="radio" id="gender_female" value="f" name="gender"/>checkbox the required Must be selected   
<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />checkbox the minlength Represents the minimum number that must be selected ,maxlength Represents the maximum number of selections ,rangelength:[2,3] Represents the selected number of intervals   
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, minlength:2}" />  
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />  
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />  
select the required Represents selected value Can't be empty   
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">  
<option value=""></option>  
<option value="1">Buga</option>  
<option value="2">Baga</option>  
<option value="3">Oi</option>  
</select>  
select the minlength Represents the minimum number of selections (multiple choices)  select ) ,maxlength Represents the maximum number of selections ,rangelength:[2,3] Represents the selected number of intervals 
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">  
<option value="b">Banana</option>  
<option value="a">Apple</option>  
<option value="p">Peach</option>  
<option value="t">Turtle</option>  
</select>  


Related articles: