Getting started with jquery validate. js Form Verification

Source: Internet
Author: User
Tags dateformat valid email address

I have reprinted an article written by my predecessors and modified it for record only.
First paste the code of a major Chinese company:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function lang (key ){
Mylang = {
'Ls _ input_myb': 'enter your account ',
'Ls _ myb_email ': 'Roaming coin account is the email address ',
'Ls _ login_password ': 'enter your logon password ',
'Ls _ password_length ': 'The password length is between {0}-{1 ',
'Ls _ input_captcha ': 'Enter the verification code ',
'Ls _ captcha_length ': 'verification code length: {0} bit ',
'Ls _ account_email ': 'account name: email address ',
'':''
};
Return mylang [key];
}
</Script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# LoginForm"). validate ({
Rules :{
UEmail :{
Required: true,
Email: true
},
UPassword :{
Required: true,
Rangelength: [6, 30]
}
},
Messages :{
UEmail :{
Required: lang ('ls _ input_myb '),
Email: lang ('ls _ myb_email ')
},
UPassword :{
Required: lang ('ls _ login_password '),
Rangelength: $. format (lang ('ls _ password_length '))
}
},
ErrorPlacement: function (error, element ){
Var placement = $ (element. parent ("td "). parent ("tr "). next ("tr "). find ("td "). get (1 ));
Placement. text ('');
Error. appendTo (placement );
},
Onkeyup: false
});
Var accountTipsText = lang ('ls _ account_email ');
$ ("# UEmail"). focus (function (){
If (! $ (This). parent (). parent (). next (). find ('td '). get (1). text ()){
Optional (((this).parent().parent().next().find('td'{.get(1}}.html ('<span class = "font_888_8">' + accountTipsText + '</span> ');
}
Watermark (this).css ('color', '#000 ');
}). Focus ();
});
</Script>

I started from this example. In fact, this example almost contains the essence of jquery. validate. js. If you fully understand this code, it is basically an entry point.
I think that when I used to simulate futures web pages online, I wrote my own code to judge them. They were actually naive and dead ............
The following is a complete article.
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
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.
<Script src = "../js/messages_cn.js" type = "text/javascript"> </script>
Usage
1. Write the validation rule to the control.
Copy codeThe Code is as follows:
<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 = "">
<Label for = "firstname"> Firstname </label>
<Input id = "firstname" name = "firstname" class = "required"/>
<Label for = "email"> email </label>
<Input id = "email" name = "email" class = "required email"/>
<Label for = "password"> Password </label>
<Input id = "password" name = "password" type = "password" class = "{required: true, minlength: 5}"/>
<Label for = "confirm_password"> Confirm Password </label>
<Input id = "confirm_password" name = "confirm_password" type = "password" class = "{required: true, minlength: 5, failed to: '# password'}"/>
<Input class = "submit" type = "submit" value = "Submit"/>
</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.
Copy codeThe Code is as follows:
$ (). 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 = "">
<Label for = "firstname"> Firstname </label>
<Input id = "firstname" name = "firstname"/>
<Label for = "email"> email </label>
<Input id = "email" name = "email"/>
<Label for = "password"> Password </label>
<Input id = "password" name = "password" type = "password"/>
<Label for = "confirm_password"> Confirm Password </label>
<Input id = "confirm_password" name = "confirm_password" type = "password"/>
<Input class = "submit" type = "submit" value = "Submit"/>
</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
Common methods and precautions
1. use other methods to replace the default SUBMIT
Copy codeThe Code is as follows:
$ (). 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.
Copy codeThe Code is as follows:
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"> </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>
</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 as text for IE
Label.html (""). 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
Copy codeThe Code is as follows:
// 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.
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
<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.
Copy codeThe Code is as follows:
<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:
<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>

The article layout is messy. It's just a record of your own ~~

Related Article

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.