The JQuery validate validation framework is detailed

Source: Internet
Author: User
Tags dateformat valid email address

jquery Check official website address: http://bassistance.de/jquery-plugins/jquery-plugin-validation

First, Import JS Library

<script type= "Text/javascript" src= "<%=path%>/validate/jquery-1.6.2.min.js" ></script>< Script type= "Text/javascript" src= "<%=path%>/validate/jquery.validate.min.js" ></script>

Note: <%=request.getcontextpath ()%> returns the root path of the Web project.

Second, the default check rule

(1), Required:true               must lose field (2), Remote: "remote-valid.jsp"   using Ajax method call remote-valid.jsp Validation input value (3), Email:true                  Must enter the correct format of e-mail (4), Url:true                    must enter the correct format of the URL (5), Date:true                   must enter the correct format of the date, the date check IE6 error, with caution (6), Dateiso:true                You must enter the correct format for the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not validate the validity (7), Number:true                 must enter a valid number (negative, decimal) (8), Digits:true                 Must enter an integer (9), Creditcard:true             must enter a valid credit card number (10), Equalto: "#password"        input value must be the same as #password (11), Accept:                    Enter a string with a valid suffix name (the suffix of the uploaded file) (12), a string with a                maximum input length of 5 (Kanji maxlength:5 one character) (13), and a string with a               minimum length of 10 for the Minlength:10 input (Chinese characters are counted as one character) (14), rangelength:[5,10]         The input length must be between 5 and 10 string ") (Chinese characters counted one character) (15), range:[5,10]               input values 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

Third, the default hints

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 E In. ', digits: ' Please enter only digits ', CreditCard: ' Please enter a valid credit card number. ', Equalto: ' Please enter the Same value again. ", Accept:" Please enter a value with a valid extension. ", MaxLength: $.validator.format (" Please enter no M Ore than {0} characters. "), MinLength: $.validator.format (" Please enter at least {0} characters. "), Rangelength: $. Validator.format ("Please enter a value of between {0} and {1} characters long."), Range: $.validator.format ("Please enter a VA Lue between {0} and {1}. "), Max: $.validator.format (" Please enter a value of less than or equal to {0}. "), min: $.validator.for Mat ("Please enter a value greater than or equal to {0}. ")}, 

If you need to modify, you can add in the JS code:

$.extend ($.validator.messages, {    required: "Required field",    remote: "Please fix this field",    email: "Please enter the correct format of e-mail",    URL: " Please enter a valid URL ", date    :" Please enter a valid date ",    dateiso:" Please enter a valid date (ISO). ",    Number:" Please enter a valid digit ",    digits:" Enter only integers ",    creditcard: "Please enter a valid credit card number",    equalto: "Please enter the same value again",    Accept: "Please enter a string with legal suffix name",    maxlength: $. Validator.format ("Please enter a string with a maximum length of {0}"),    minlength: $.validator.format ("Enter a string with a minimum length of {0}"),    Rangelength: $.validator.format ("Please enter a string between {0} and {1}"),    Range: $.validator.format ("Enter a value between {0} and {1}"),    Max: $.validator.format ("Enter a value up to {0}"),    min: $.validator.format ("Enter a value of minimum {0}")});

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

<script type= "Text/javascript" src= "<%=path%>/validate/messages_cn.js" ></script>

Iv. Mode of Use
1, metadata usage, officer rules written into the control

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><% String Path = Request.getcontextpath ()    ; String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Using the class= "{}" method, the package must be introduced: jquery.metadata.js;
You can use the following methods to modify the prompt content: class= "{required:true,minlength:5,messages:{required: ' Please input content '}}";
When using the Equalto keyword, the following must be enclosed in quotation marks, as follows: class= "{required:true,minlength:5,equalto: ' #password '}".

2, officer rules written into the JS code

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><% String Path = Request.getcontextpath ()    ; String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Five, common methods and attention problems
1. Replace the default submit in other ways

$ (function () {   $ ("#signupForm"). Validate ({        submithandler:function (form) {            alert ("submit!");               Form.submit ();});        

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

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

2, Debug, only verify not submit form
If this parameter is true, then the form will not be submitted, only check, debugging is very convenient

$ (function () {    $ ("#signupForm"). Validate ({        debug:true    });});

If more than one form in a page wants to be set to debug, use the
$.validator.setdefaults ({
Debug:true
})

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

4. Change the location of the error message display
Errorplacement:callback

Default: Put the error message behind the validated element
Indicates where the error is placed, by default: Error.appendto (Element.parent ()), where the error message is placed after the element being validated
Errorplacement:function (Error, Element) {
Error.appendto (Element.parent ());
}

Example

<tr> <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= "/></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_e U "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 C            lass= "label" >&nbsp;</td> <td class= "field" colspan= "2" > <div id= "Termswrap" > <input id= "terms" type= "checkbox" name= "terms"/> <Label id= "lterms" for= "terms" >i has 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 to display the error message in <TD class= "status" ></td>, if Radio is displayed in <td></td>, if the checkbox is displayed behind the content

Errorclass:string Default: "Error"
Specify the CSS class name for the error prompt, and you can customize the style of the error prompt

Errorelement:string Default: "Label"
Tag error with what label, default is label you can change to EM

Errorcontainer:selector
Display or hide the verification information, can automatically implement error messages appear when the container properties to display, error-free hiding, not very useful
Errorcontainer: "#messageBox1, #messageBox2"

Errorlabelcontainer:selector
Put the error message in a single container.

Wrapper:string
What label to wrap up the top errorelement

In general, these three properties are used simultaneously to implement the ability to display all error hints within a container and to automatically hide when no information is available.
Errorcontainer: "Div.error",
Errorlabelcontainer: $ ("#signupForm div.error"),
Wrapper: "Li"

5. Change the style of the error message display
Set the style of the error prompt, you can increase the icon display, in the system has established a VALIDATION.CSS dedicated to maintain the verification file style

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

6. Each field is validated by executing the function
Success:string,callback

The element to be validated passes the validated action, if followed by a string, as a CSS class, or with 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 validation element, the style defined in the CSS <style>label.valid {}</style>
Success: "Valid"

7, validation of the trigger mode modification
Although the following are Boolean, it is recommended that you do not add them unless you want to change to false.
A.onsubmit:boolean Default:true
Validation at commit time. Set only false to verify with other methods
B.onfocusout:boolean Default:true
Loss of focus is validation (not including Checkboxes/radio buttons)
C.onkeyup:boolean Default:true
Validated at KeyUp.
D.onclick:boolean Default:true
Validate when clicked on checkboxes and radio
E.focusinvalid:boolean Default:true
When a form is submitted, a form that does not pass validation (the first one or an unauthenticated form that receives the focus before it is submitted) gets the focus
F.focuscleanup:boolean Default:false
If true, removes the error prompt when the element that is not validated is focusable. Avoid using with the Focusinvalid

8. Asynchronous authentication
Remote:url
Using AJAX to authenticate, the default is to submit the current validated value to the remote address, if you need to commit additional values, you can use the data option

Example one: Remote: "check-email.php" Example two: remote: {    URL: "check-email.php",     //spooler    type: "POST",               //Data sending method    dataType: "JSON",           //Accept Data format       : {                     //data to be passed        username:function () {            return $ ("#username"). Val ();}}}    

The remote address can only output "true" or "false" and cannot have additional output.

9. Add a custom check
Addmethod:name, method, message
Custom Validation Methods

Chinese characters two bytes 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 you enter a value between {0}-{1} bytes ( 2 bytes in a Chinese text));//ZIP code validation   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");

1. To add in the Additional-methods.js file or add it in jquery.validate.js
Recommendations are generally written in the Additional-methods.js file

2. In the Messages_cn.js file add: Iszipcode: "Can only include Chinese characters, English letters, numbers and underscores",
Add a reference to the Additional-methods.js file before calling.

10. Verification of Radio and checkbox, select

A required of 1.radio indicates that a <input type= "Radio" id= "Gender_male" value= "M" name= "gender"/"class=" must be selected. ><input type= "Radio" id= "Gender_female" value= "F" name= "gender"/>2.checkbox indicates that required <input must be selected " CheckBox "class=" checkbox "id=" Agree "Name=" agree "class=" {required:true} "/>checkbox indicates the minimum number that must be selected, MaxLength indicates the maximum number of selected, rangelength:[2,3] indicates the selected range <input type= "checkbox" id= "Spam_email" value= "email" name= "spam[" Class= "{required:true, minlength:2}"/><input type= "checkbox" id= "Spam_phone" value= "Phone" name= "spam[]"/> <input type= "checkbox" id= "Spam_mail" value= "Mail" name= "spam["/>3.select required means 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 val Ue= "3" >Oi</option></select> Select minlength indicates the minimum number selected (select), maxlength indicates the maximum number of selected, rangelength:[2,3] indicates the selected range <select id= "fruit" name= "fruit" title= "Please select at least 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 JQuery validate validation framework is detailed

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.