Introduction to Jquery.validate's use instructions _jquery

Source: Internet
Author: User
Tags dateformat wrapper

First, preparatory work
jquery version required: 1.2.6+, compatible 1.3.2

Website address: http://jqueryvalidation.org/

Second, the default checksum rule
(1) Required:true must be lost field
(2) Remote: "check.php" use Ajax method to invoke check.php validate input value
(3) Email:true must enter the correct format email
(4) Url:true must enter the URL in the correct format
(5) Date:true must enter a date in the correct format
(6) Dateiso:true must enter the correct format of the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not verify the validity
(7) Number:true must enter a valid number (negative, decimal)
(8) Digits:true must enter an integer
(9) CreditCard: Must enter the legal credit card number
(a) Equalto: "#field" input value must be the same as #field
(one) Accept: Enter a string with a valid suffix name (the suffix of the uploaded file)
(Maxlength:5) A string with a maximum of 5 input length (Chinese characters are counted as one character)
(Minlength:10) A string with a minimum input length of 10 (Chinese characters are counted as one character)
(rangelength:[5,10] Enter a string that must be between 5 and 10) (Chinese characters are counted as one character)
() range:[5,10] The input value must be between 5 and 10
() Max:5 input value cannot be greater than 5
(min:10) input value cannot be less than 10

Third, the default hint

Copy Code code as follows:

Messages: {
Required: "This field is required.",
Remote: "Please fix this field.",
Email: "Please enter a valid e-mail 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.",
Number: "Please enter a valid number.",
Numberde: "Bitte geben Sie eine Nummer.",
Digits: "Please enter only digits",
CreditCard: "Please enter a valid 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 in the JS code:
Copy Code code as follows:

Jquery.extend (JQuery.validator.messages, {
Required: "Required fields",
Remote: "Please fix this field",
Email: "Please enter the correct format email",
URL: "Please enter a valid URL",
Date: "Please enter a valid date",
Dateiso: "Please enter a valid date (ISO).",
Number: "Please enter legal numbers",
Digits: "Only integers can be entered",
CreditCard: "Please enter a valid credit card number",
Equalto: "Please enter the same value again",
Accept: "Please enter a string with a legal suffix name",
Maxlength:jQuery.validator.format ("Please enter a string with a maximum length of {0}"),
Minlength:jQuery.validator.format ("Please enter a string with a length of at least {0}"),
Rangelength:jQuery.validator.format ("Please enter a string between {0} and {1}"),
Range:jQuery.validator.format ("Please enter a value between {0} and {1}"),
Max:jQuery.validator.format ("Please enter a value of max {0}"),
Min:jQuery.validator.format ("Please enter a value of min {0}")
});

Recommended practice, put this file into Messages_cn.js, and introduce it into the page

Iv. Mode of Use
1. Officers transferred Guevara rules are written to the control

Copy Code code as follows:

<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" &GT;&LT;/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=: ' #password '} '/>
</p>
<p>
<input class= "Submit" type= "submit" value= "Submit"/>
</p>
</form>

With class= "{}", you must introduce the package: Jquery.metadata.js can modify the hint by using the following method:
Class= "{required:true,minlength:5,messages: {required: ' Please enter '}}" when using the Equalto keyword, the following must be enclosed in quotation marks, as follows:
Class= "{required:true,minlength:5,equalto: ' #password '}" another way, using keywords: meta (for metadata use other plug-ins you want to wrap your validation rules This particular option can be used in their own projects.
Tell the validation plugin to look inside a validate-property into metadata for validation rules.
For example:
Copy Code code as follows:

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

There is another way:
Copy Code code as follows:

$.metadata.settype ("attr", "validate") so that you can use the validate= "{required:true}" method, or class= "required", but class= "{required : True,minlength:5} "will not work 2. Officers transferred Guevara rules written 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 your name",
Email: {
Required: "Please enter your email address",
Email: "Please enter the correct email address"
},
Password: {
Required: "Please enter the password",
Minlength:jQuery.format ("Password cannot be less than {0} characters")
},
Confirm_password: {
Required: "Please enter confirmation password",
MinLength: "Confirm password cannot be less than 5 characters",
Equalto: "Two input passwords inconsistent inconsistent"
}
}
});
//messages, if a control does not have a message, the default information is invoked

Copy Code code as follows:

<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: The value of the "#aa: Checked" expression is true, you need to verify
Required:function () {} returns True, the table requires validation
Two of the elements that are commonly used in the form that need to be filled in or not filled in at the same time

V. Common methods and attention problems

1. Replace the default submit$ (). Ready in other ways (function () {
$ ("#signupForm"). Validate ({
Submithandler:function (form) {
Alert ("submitted");
Form.submit ();
}
});
});

You can set the default value for validate, as follows:
$.validator.setdefaults ({
Submithandler:function (form) {alert ("submitted!"); Form.submit (); }
});

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

2.debug, if this argument is true, the form will not be submitted, only check, easy to debug
$ (). Ready (function () {
$ ("#signupForm"). Validate ({
Debug:true
});
});

If you have more than one form in a page, use the
$.validator.setdefaults ({
Debug:true
})

3.ignore: Ignoring certain elements not validated
Ignore: ". Ignore"

4.errorplacement:callback Default: Put the error message behind the validated element

Indicates where the error was placed, by default: Error.appendto (Element.parent ()), where the error message is placed behind the validated element
Errorplacement:function (Error, Element) {
Error.appendto (Element.parent ());
}//Example:

Copy Code code as follows:

<tr>
&LT;TD class= "label" ><label id= "Lfirstname" for= "FirstName" >first name</label></td>
&LT;TD class= "field" ><input id= "FirstName" name= "FirstName" "type=" text "value=" "maxlength=" >
&LT;TD class= "status" ></td>
</tr>
<tr>
&LT;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>
&LT;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>
&LT;TD class= "label" > </td>
&LT;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 ());
}

The function of the code is: usually the error message is displayed in, if it is radio displayed in, if the checkbox is displayed in the back of the content errorclass:string Default: "Error"

Specifies the CSS class name for the error hint, and you can customize the style of the error hint errorelement:string Default: "Label"

Labeling errors with what tags, the default is label you can change to Emerrorcontainer:selector

Display or hide validation information, you can automatically implement error message when the container properties into display, no error hidden, not very useful

Errorcontainer: "#messageBox1, #messageBox2" Errorlabelcontainer:selector

Put the error message together in a container. Wrapper:string

What label do you use to wrap up the top errorelement? These three properties are used at the same time, implement the function of displaying all the error hints in a container, and automatically hide Errorcontainer when there is no information: "Div.error",

Errorlabelcontainer: $ ("#signupForm div.error"),
Wrapper: "Li" sets the style of the error hint, you can increase the icon to display 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

The element to be validated is validated by the action, if followed by a string, as a CSS class, can also be followed by a function
Success:function (label) {
Set as text for IE
Label.html (""). AddClass ("checked");
Label.addclass ("valid"). Text ("ok!")
}

Add "valid" to validation elements, styles defined in CSS
Success: "Valid" Nsubmit:boolean default:true

Validation at time of submission. Set only false to validate in other ways
Onfocusout:boolean Default:true

Loss of focus is validation (excluding Checkboxes/radio buttons)
Onkeyup:boolean Default:true

Validated at keyup time.
Onclick:boolean Default:true

Validate when checkboxes and radio click
Focusinvalid:boolean Default:true

When a form is submitted, a form that is not validated (the first or the failed validated form that has the focus before it is submitted) receives the focus
Focuscleanup:boolean Default:false

If it is true, remove the error prompt when the element that is not validated gets the focus. Avoid resetting the form with//with Focusinvalid

Copy Code code as follows:

$ (). Ready (function () {
var validator = $ ("#signupForm"). Validate ({
Submithandler:function (form) {
Alert ("submitted");
Form.submit ();
}
});
$ ("#reset"). Click (function () {
Validator.resetform ();
});});

Using Ajax for validation, the default is to commit the currently validated value to the remote address, and you can use the data option if you need to submit additional values
Copy Code code as follows:

Remote: {
URL: "check-email.php",//Background handler
Type: "POST",//How data is sent
DataType: "JSON",//Accept data format
Data: {//To be passed
Username:function () {
Return $ ("#username"). Val ();
}
}
}

Remote addresses can only output "true" or "false" and cannot have other output addmethod:name, method, message
Custom Validation Methods
Copy Code code as follows:

Two bytes in 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 ("Make sure the value entered is between {0}-{1} bytes (2 bytes in one)");
ZIP Code Verification
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");

Copy Code code as follows:

The required of the validation radio for radio and checkbox, select must select a
<input type= "Radio" id= "Gender_male" value= "M" name= "gender" class= "{required:true}"/>
Gender_female representation of <input type= "Radio" id= "value=" name= "F" gender "/>checkbox" required must be selected
<input type= "checkbox" class= "checkbox" id= "Agree" Name= "agree" class= "{required:true}"/> The minlength of the checkbox indicates the minimum number that must be selected, MaxLength represents the maximum number of checks, and rangelength:[2,3] represents the selected range
<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["/>
The required of the select indicates that the selected value cannot 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 the select represents the minimum number selected (selectable Select), maxlength represents the maximum number of selections, and rangelength:[2,3] represents the selected range
Copy Code code as follows:

The required of the validation radio for radio and checkbox, select must select a
<input type= "Radio" id= "Gender_male" value= "M" name= "gender" class= "{required:true}"/>
Gender_female representation of <input type= "Radio" id= "value=" name= "F" gender "/>checkbox" required must be selected
<input type= "checkbox" class= "checkbox" id= "Agree" Name= "agree" class= "{required:true}"/> The minlength of the checkbox indicates the minimum number that must be selected, MaxLength represents the maximum number of checks, and rangelength:[2,3] represents the selected range
<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["/>
The required of the select indicates that the selected value cannot 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 the select represents the minimum number selected (selectable Select), maxlength represents the maximum number of selections, and rangelength:[2,3] represents the selected range

<select id= "fruit" name= Fruit "title=" Please select at least two "fruits" {class=, required:true} "Minlength:2 E= "multiple" >
<option value= "B" >Banana</option>
<option value= "a" >Apple</option>
<option value= "P" >Peach</option>
<option value= "T" >Turtle</option>
</select>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.