Here reproduced an article written by the predecessors, in my own understanding of the modified, only for record.
First paste a large domestic company code:
Copy Code code as follows:
<script type= "Text/javascript" >
function lang (key) {
Mylang = {
' Ls_input_myb ': ' Please enter your account ',
' Ls_myb_email ': ' Roaming currency account for email address ',
' Ls_login_password ': ' Please enter your login password ',
' Ls_password_length ': ' The password length is between {0}-{1} bit ',
' Ls_input_captcha ': ' Please enter the verification code ',
' Ls_captcha_length ': ' The length of the verification code is {0} bit ',
' Ls_account_email ': ' Account name is 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 '). (1)). Text ()) {
$ (a). Parent (). Parent (). Next (). Find (' TD '). Get (1)). HTML (' <span class= ' font_888_8 ' > ' + accounttipstext + ' </span> ');
}
$ (this). CSS (' color ', ' #000 ');
). focus ();
});
</script>
I started with this example, and in fact this example almost contains the essence of jquery.validate.js, if you fully understand the code is basically a primer.
Think of the past to do the Futures Web online simulation of the time to write their own code to judge, real naïve died ...
The following is a complete introduction to the article.
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
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
<script src= ". /js/messages_cn.js "type=" Text/javascript "></script>
How to use
1. Officers transferred Guevara rules are written to the control
Copy Code code 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" >E-Mail</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=: ' #password '} '/>
<input class= "Submit" type= "submit" value= "Submit"/>
</form>
The package must be introduced in the way class= ' {} ' is used: jquery.metadata.js
You can modify the hint by using the following methods:
Class= ' {required:true,minlength:5,messages:{required: ' Please enter the content '}} '
When using the Equalto keyword, the following text must be enclosed in quotation marks, as follows:
Class= "{required:true,minlength:5,equalto: ' #password '}"
Another way to use keywords: meta (for meta data use other plug-ins you want to wrap your validation rules in their own projects can use this particular option)
Tell the validation plugin to look inside a validate-property into 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");
This can be done using validate= "{required:true}", or class= "required", but class= "{required:true,minlength:5}" will not work
2. Officers transferred Guevara rules are written in the code
Copy Code code 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,
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
<form id= "Signupform" method= "Get" action= "" >
<label for= "FirstName" >Firstname</label>
<input id= "FirstName" name= "FirstName"/>
<label for= "Email" >E-Mail</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
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
Common methods and attention problems
1. Replace the default submit in other ways
Copy Code code as follows:
$ (). Ready (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
Copy Code code 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=" >
<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 function of the code is to display the error message in the <TD class= "status" ></td>, if the radio is displayed in <td></td>, if the checkbox is displayed behind 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 EM
Errorcontainer: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 will you use to wrap up the errorelement?
Typically, these three properties are used simultaneously to display all the error hints in a container, and to automatically hide when there is no information
Errorcontainer: "Div.error",
Errorlabelcontainer: $ ("#signupForm div.error"),
Wrapper: "Li"
To set the style of the error hint, you can increase the icon 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 the validation element, the style defined in the CSS <style>label.valid {}</style>
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 working with Focusinvalid
Copy Code code as follows:
Resetting a form
$ (). Ready (function () {
var validator = $ ("#signupForm"). Validate ({
Submithandler:function (form) {
Alert ("submitted");
Form.submit ();
}
});
$ ("#reset"). Click (function () {
Validator.resetform ();
});
});
Remote:url
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: "check-email.php"
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
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");
Verification of Radio and checkbox, select
Radio's required indicates that you must select a
<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 representation of 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 represents the maximum number of checks, and rangelength:[2,3] represents the selected range
Copy Code code 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["/>
The required of the select indicates that the selected value cannot be empty
Copy Code code 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 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:
<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>
Article layout is a bit messy, just their own records ~ ~