Jquery. validate instructions

Source: Internet
Author: User
Tags valid email address

I. Preparations
JQuery version: 1.2.6 +, compatible with 1.3.2

Official website address: http://jqueryvalidation.org/

Ii. Default verification rules
(1) required: required field for true
(2) remote: "check. php" uses ajax to call check. php to verify the input value.
(3) email: true: You must enter an email in the correct format.
(4) url: true must enter the url in the correct format
(5) date: true must be a date in the correct format
(6) dateISO: true: the date (ISO) in the correct format must be entered. For example, 2009-06-23,1998/01/22: only the format is verified and the validity is not verified.
(7) number: true: a valid number (negative number, decimal number) must be entered)
(8) digits: true must be an integer.
(9) creditcard: a valid credit card number must be entered.
(10) must to: "# field" the input value must be the same as # field
(11) accept: enter a string with a valid suffix (the suffix of the uploaded file)
(12) maxlength: A string with a maximum length of 5 characters)
(13) minlength: 10 string with a minimum input length of 10 (one character for Chinese characters)
(14) rangelength: [5, 10] The input length must be a string between 5 and 10. ") (a Chinese character is a single character)
(15) range: [5, 10] The input value must be between 5 and 10.
(16) max: 5 input value cannot be greater than 5
(17) min: 10 input value cannot be less than 10

3. default prompt
Copy codeThe Code is as follows:
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 .",
Failed to: "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 }.")
},

To modify the parameters, add the following to the js Code:
Copy codeThe Code is as follows:
JQuery. extend (jQuery. validator. messages ,{
Required: "required fields ",
Remote: "Please correct this field ",
Email: "Please enter an email in the correct format ",
Url: "enter a valid url ",
Date: "enter a valid date ",
DateISO: "enter a valid date (ISO ).",
Number: "enter a valid number ",
Digits: "Only integers can be entered ",
Creditcard: "enter a valid credit card number ",
Similar to: "Please enter the same value again ",
Accept: "enter a string with a valid suffix ",
Maxlength: jQuery. validator. format ("enter a string with a maximum length of {0 "),
Minlength: jQuery. validator. format ("enter a string with at least {0} length "),
Rangelength: jQuery. validator. format ("enter a string between {0} and {1 "),
Range: jQuery. validator. format ("enter a value between {0} and {1 "),
Max: jQuery. validator. format ("enter a maximum value of {0 "),
Min: jQuery. validator. format ("enter a minimum value of {0 ")
});

We recommend that you add this file to messages_cn.js and introduce it on the page.

Iv. Usage
1. Write the validation rule to the control.
Copy codeThe Code is 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 "> </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"> email </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, failed to: '# password'}"/>
</P>
<P>
<Input class = "submit" type = "submit" value = "Submit"/>
</P>
</Form>

To use class = "{}", you must introduce the package: jquery. metadata. js can use the following method to modify the prompt content:
Class = "{required: true, minlength: 5, messages: {required: 'Enter the content'}" when using the sort to keyword, the following content must be enclosed by quotation marks, the following code:
Class = "{required: true, minlength: 5, failed to: '# password'}" another method, using the Keyword: meta (to use other plug-ins for metadata, You need to wrap your verification rules and use this special option in their own projects)
Tell the validation plugin to look inside a validate-property in metadata for validation rules.
For example:
Copy codeThe Code is as follows:
Meta: "validate" <input id = "password" name = "password" type = "password" class = "{validate: {required: true, minlength: 5} "/>

There is another way:
Copy codeThe Code is as follows:
$. Metadata. setType ("attr", "validate"); in this way, you can use validate = "{required: true}", or class = "required", but class = "{required: true, minlength: 5} "will not work 2. write the validation rule to the code
$ (). Ready (function (){
$ ("# SignupForm"). validate ({
Rules :{
Firstname: "required ",
Email :{
Required: true,
Email: true
},
Password :{
Required: true,
Minlength: 5
},
Confirm_password :{
Required: true,
Minlength: 5,
Failed to: "# password"
}
},
Messages :{
Firstname: "enter your name ",
Email :{
Required: "Enter the Email address ",
Email: "enter the correct email address"
},
Password :{
Required: "enter the password ",
Minlength: jQuery. format ("the password cannot be less than {0} characters ")
},
Confirm_password :{
Required: "enter the password ",
Minlength: "The password cannot be less than five characters ",
Similar to: "inconsistent passwords entered twice"
}
}
});
}); // At messages, if a control does not have a message, the default message will be called.

Copy codeThe Code is as follows:
<Form id = "signupForm" method = "get" action = "">
<P>
<Label for = "firstname"> Firstname </label>
<Input id = "firstname" name = "firstname"/>
</P>
<P>
<Label for = "email"> email </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
If the value of the required: "# aa: checked" expression is true, you need to verify
Required: function () {} returns true, which must be verified during table verification.
The following two types of elements are commonly used: elements that need to be filled in or out of the form

5. common methods and precautions

1. use other methods to replace the default SUBMIT $ (). ready (function (){
$ ("# SignupForm"). validate ({
SubmitHandler: function (form ){
Alert ("submitted ");
Form. submit ();
}
});
});

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

To submit a form, use form. submit () instead of $ (form). submit ()

2. debug. If this parameter is set to true, the form will not be submitted and only be checked. This is very convenient during debugging.
$ (). Ready (function (){
$ ("# SignupForm"). validate ({
Debug: true
});
});

If a page contains multiple forms, use
$. Validator. setDefaults ({
Debug: true
})

3. ignore: ignore some elements and do not verify
Ignore: ". ignore"

4. errorPlacement: Callback Default: Put the error message behind the Validation Element

Specifies the location where the error is placed. The default situation is: error. appendTo (element. parent (); that is, the error information is placed after the verification element.
ErrorPlacement: function (error, element ){
Error. appendTo (element. parent ());
} // Example:
Copy codeThe Code is as follows:
<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 ());
}

The function of the Code is: Generally, the error information is displayed in, if radio is displayed in, if the checkbox is displayed after the content errorClass: String Default: "error"

Specifies the css Class Name of the error message. You can customize the style errorElement: String Default: "label" of the error message"

Label used to mark errors. The default label can be changed to emerrorContainer: Selector.

Display or hide the verification information. The Container attribute can be automatically displayed when an error message is displayed, and hidden when no error occurs, which is of little use.

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

Put the error information in a container. Wrapper: String

Label used to pack the preceding errorELement. Generally, these three attributes are used at the same time to display all error prompts in a container. If there is no information, the errorContainer is automatically hidden: "div. error ",

ErrorLabelContainer: $ ("# signupForm div. error "),
Wrapper: "li": Set the error message style. You can add the input. error {border: 1px solid red;} icon to display ;}
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 action after the element to be verified passes the verification. If it is followed by a string, it will be treated as a css class or a function.
Success: function (label ){
// Set as text for IE
Label.html (""). addClass ("checked ");
// Label. addClass ("valid"). text ("OK! ")
}

Add "valid" to the verification element and define the style in CSS
Success: "valid" nsubmit: Boolean Default: true

Verification upon submission. use other methods to verify if the value is false.
Onfocusout: Boolean Default: true

Missing focus is verification (excluding checkboxes/radio buttons)
Onkeyup: Boolean Default: true

Verification during keyup.
Onclick: Boolean Default: true

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

After a form is submitted, a form that has not passed the verification (the first form or a form that has not passed the verification that has received the focus before submission) will get the focus
FocusCleanup: Boolean Default: false

If this parameter is set to true, the error message is removed when the unverified element gets the focus. Avoid using the form with the focusInvalid // reset the form
Copy codeThe Code is as follows:
$ (). Ready (function (){
Var validator = $ ("# signupForm"). validate ({
SubmitHandler: function (form ){
Alert ("submitted ");
Form. submit ();
}
});
$ ("# Reset"). click (function (){
Validator. resetForm ();
});});

If you use ajax for verification, the value of the current verification is submitted to the remote address by default. If you need to submit other values, you can use the data option.
Copy codeThe Code is as follows:
Remote :{
Url: "check-email.php", // background Handler
Type: "post", // data transmission method
DataType: "json", // accept the data format
Data: {// data to be passed
Username: function (){
Return $ ("# username"). val ();
}
}
}

The remote address can only output "true" or "false", but cannot output addMethod: name, method, message
Custom Verification Method
Copy codeThe Code is as follows:
// Two Chinese characters
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 that the input value is between {0}-{1} bytes (two bytes for one text )"));
// Postal code verification
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 ");

Copy codeThe Code is as follows:
Verify radio, checkbox, and select. required indicates that
<Input type = "radio" id = "gender_male" value = "m" name = "gender" class = "{required: true}"/>
<Input type = "radio" id = "gender_female" value = "f" name = "gender"/> the required field of the checkbox indicates that the checkbox 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 indicates the maximum number of selected items, and rangelength: [2, 3] indicates the selected number 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 []"/>
Select required indicates that the selected value cannot be blank.
<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 indicates the minimum number of selected items (multiple select options are available), maxlength indicates the maximum number of selected items, and rangelength: [2, 3] indicates the selected number range.
Copy codeThe Code is as follows:
Verify radio, checkbox, and select. required indicates that
<Input type = "radio" id = "gender_male" value = "m" name = "gender" class = "{required: true}"/>
<Input type = "radio" id = "gender_female" value = "f" name = "gender"/> the required field of the checkbox indicates that the checkbox 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 indicates the maximum number of selected items, and rangelength: [2, 3] indicates the selected number 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 []"/>
Select required indicates that the selected value cannot be blank.
<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 indicates the minimum number of selected items (multiple select options are available), maxlength indicates the maximum number of selected items, and rangelength: [2, 3] indicates the selected number range.

<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>

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.