Jquery. Validate. js Form Verification

Source: Internet
Author: User
Tags valid email address
Jquery. Validate. js Form validation this article is transferred from: http://hi.baidu.com/greenandcoffee/blog/item/5ebe5850e2cfbb551138c24d.html

I. Prerequisites
Http://bassistance.de/jquery-plugins/jquery-plugin-validation/
API: http://jquery.bassistance.de/api-browser/plugins.html
Current version: 1.5.5
Jquery version: 1.2.6 +, compatible with 1.3.2
<SCRIPT src = "../JS/jquery. js" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "../JS/jquery. Validate. js" type = "text/JavaScript"> </SCRIPT>

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
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:
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.
<SCRIPT src = "../JS/messages_cn.js" type = "text/JavaScript"> </SCRIPT>

Iv. Usage
1. Write the validation rule to the control.
<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 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.
You 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 in quotation marks, as shown in the following code:
Class = "{required: True, minlength: 5, failed to: '# password '}"
Another way is to use keywords: Meta (for metadata to use other plug-ins, You need to wrap your verification rules to 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:
Meta: "Validate"
<Input id = "password" name = "password" type = "password" class = "{validate: {required: True, minlength: 5}"/>

There is another way:
$. Metadata. settype ("ATTR", "Validate ");
In this way, validate = "{required: true}" or class = "required" can be used, but class = "{required: True, minlength: 5}" will not work.

2. Write the validation rules 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"
}
}
});
});
// If a control does not have a message, the default message is called.

<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:
<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;">
<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;">
<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"> & nbsp; </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 purpose of the code is to display the error information in <TD class = "status"> </TD>, if radio is displayed in <TD> </TD>, 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 of the error message.
Errorelement: String default: "label"
Label used to mark errors. The default label can be changed to em.
Errorcontainer: 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 above errorelement
These three attributes are usually used at the same time to display all error prompts in a container and hide them automatically when there is no information.
Errorcontainer: "Div. error ",
Errorlabelcontainer: $ ("# signupform Div. error "),
Wrapper: "Li"

Set the style of the error message. You can add an icon to display it.
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 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 & nbsp; as text for IE
Label.html ("& nbsp;"). addclass ("checked ");
// Label. addclass ("valid"). Text ("OK! ")
}
Add "valid" to the verification element and define the style <style> label. Valid {}</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 it with focusinvalid

// Reset the form
$ (). Ready (function (){
VaR validator = $ ("# signupform"). Validate ({
Submithandler: function (form ){
Alert ("submitted ");
Form. Submit ();
}
});
$ ("# RESET"). Click (function (){
Validator. resetform ();
});
});

Remote: URL
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.
Remote: "check-email.php"
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 other parameters.

Addmethod: name, method, message
Custom Verification Method

// 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 ");

Radio, checkbox, and select Verification
Radio required indicates that one of
<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 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 checkbox indicates the minimum number of required items, 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.