JQuery Validate Content

Source: Internet
Author: User
Tags dateformat

Import JS Library
<script src= ". /js/jquery.js "type=" Text/javascript "></script><script src=". /js/jquery.validate.js "type=" Text/javascript "></script>
Default validation rules
Serial Number rules Description
1 Required:true The field that must be entered.
2 Remote: "check.php" Use the Ajax method to call check.php to validate the input values.
3 Email:true You must enter an e-mail message in the correct format.
4 Url:true You must enter a URL in the correct format.
5 Date:true You must enter a date in the correct format. Date Check IE6 error, use with caution.
6 Dateiso:true You must enter the correct format for the date (ISO), for example: 2009-06-23, 1998/01/22. Verify the format only and do not validate the validity.
7 Number:true You must enter a valid number (negative, fractional).
8 Digits:true You must enter an integer.
9 CreditCard You must enter a valid credit card number.
10 Equalto: "#field" The input value must be the same as #field.
11 Accept Enter a string with a valid suffix name (the suffix of the upload file).
12 Maxlength:5 Enter a string with a maximum length of 5 (Chinese characters are counted as one character).
13 Minlength:10 Enter a string with a minimum length of 10 (Chinese characters are counted as one character).
14 RANGELENGTH:[5,10] Enter a string that must be between 5 and 10 (Chinese characters are counted as one character).
15 RANGE:[5,10] The input value must be between 5 and 10.
16 Max:5 The input value cannot be greater than 5.
17 Min:10 The input value cannot be less than 10.
Default prompt
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 VA Lid date (ISO). ", Datede:" Bitte geben Sie ein gültiges Datum ein. ", Number:" Please enter a valid number. ", Numb Erde: "Bitte geben Sie eine Nummer ein.", Digits: "Please enter only digits", CreditCard: "Please enter a valid cred It card number. ", Equalto:" Please enter the same value again. ", Accept:" Please enter a value with a valid Extensio N. ", MaxLength: $.validator.format (" Please enter no more than {0} characters. "), MinLength: $.validator.format (" plea Se enter at least {0} characters. "), Rangelength: $.validator.format (" Please enter a value between {0} and {1} characte RS long. "), Range: $.validator.format (" Please enter a value between {0} and {1}. "), Max: $.validator.format (" please Enter a value less thanor equal to {0}. "), Min: $.validator.format (" Please enter a value of greater than or equal to {0}. ")}, 

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

Jquery.extend (jQuery.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 Integer ", CreditCard:" Please enter a valid credit card number ", Equalto: "Please enter the same value again", Accept: "Please enter a string with a valid suffix name", Maxlength:jQuery.validator.format ("Enter a string of up to {0}"), MinLength: JQuery.validator.format ("Please enter a string with a minimum length of {0}"), Rangelength:jQuery.validator.format ("Enter a string between {0} and {1}"), Range:jQuery.validator.format ("Please enter a value between {0} and {1}"), Max:jQuery.validator.format ("Enter a value up to {0}"), min: JQuery.validator.format ("Please enter a value of minimum {0}")});

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

<script src= ". /js/messages_cn.js "type=" Text/javascript "></script>
Use mode 1, Officer rules written 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" &GT;FIRSTNAME&LT;/LABEL&G        T <input id= "FirstName" name= "FirstName" class= "required"/> </p> <p> <label for= "email" >e-mail& lt;/label> <input id= "email" name= "email" class= "required email"/> </p> <p> <label for= "Passwor D ">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,equalto: ' #password'} '/> </p> <p> <input class= "Submit" type= "submit" value= "Submit"/> </p></form >

Using class= "{}", 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 enter content '}}"

When using the Equalto keyword, the following content must be enclosed in quotation marks, as shown in the following code:

Class= "{required:true,minlength:5,equalto: ' #password '}"
2, officer rules written into the JS code
$ (). 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 name",   email: {    required: "Please enter the email address",    email: "Please enter the correct email address"   },   password: {    Required: "Please enter password",    minlength:jQuery.format ("Password cannot be less than {0} characters")   },   Confirm_password: {    Required: " Please enter the confirmation password ",    minlength:" Confirm password cannot be less than 5 characters ",    Equalto:" Two times input password inconsistent inconsistent "}}    );

Messages, if a control does not have a message, the default information is called

<form id= "Signupform" method= "Get" action= "" >    <p>        <label for= "FirstName" >firstname</ label>        <input id= "FirstName" name= "FirstName"/>    </p> <p>  <label for= "Email" >E-Mail</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.
Required: The value of the "#aa: Checked" expression is true, you need to verify.
Required:function () {} returns true to indicate that validation is required.

There are two types of elements that are commonly used in the form, which need to be filled in or not.

Common methods and attention issues 1. Replace the default SUBMIT in other ways
$ (). Ready (function () {$ ("#signupForm"). Validate ({        submithandler:function (form) {            alert ("submitted");               Form.submit ();});        

Using the AJAX approach

$ (". Selector"). Validate ({      submithandler:function (form)    {            $ (form). Ajaxsubmit ();           

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 the $ (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.

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

If more than one form in a page wants to be set to debug, use:

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

Indicates where the error was 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 ());  }

Instance

<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: in general, the error message is displayed in the <td class= "status" ></td>, if Radio is displayed in <td></td>, if it is a checkbox is displayed after the content.

Parameters type Description Default Value
Errorclass String Specifies the CSS class name for the error prompt, and you can customize the style of the error prompt. "Error"
Errorelement String Tag the error with what label, default is label, can be changed to EM. "Label"
Errorcontainer Selector Display or hide the verification information, you can automatically implement the error message appears when the container properties into the display, error-free hiding, not very useful.
Errorcontainer: "#messageBox1, #messageBox2"
Errorlabelcontainer Selector Put the error message in a single container.
Wrapper String Use any 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 style of the checksum file.

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

trigger mode description default
onsubmit Boolean Commit-time validation. Set to False to verify with other methods. true
onfocusout Boolean validation without focus (check box/radio button not included). true
onkeyup Boolean validated at KeyUp. true
onclick Boolean is validated when the check box and radio buttons are clicked. true
focusinvalid Boolean After a form is submitted, a form that does not pass validation (the first one or the one that received the focus before form) will receive the focus. true
focuscleanup Boolean If True then remove the error message when the element that is not validated is focusable 。 Avoid using with Focusinvalid. false
Reset the form $ (). Ready (function () {var validator = $ ("#signupForm"). Validate ({        submithandler:function (form) {            Alert ("submitted");               Form.submit ();        }        });    $ ("#reset"). Click (function () {        validator.resetform ();    });});
8. Asynchronous authentication
Remote:url

Using AJAX to authenticate, the default is to submit the currently validated value to the remote address, and if additional values need to be submitted, use the data option.

Remote: "check-email.php"
Remote: {    URL: ' check-email.php ',     //spooler    type: ' Post ',               //data sent    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 the value entered is between {0}-{1} bytes (2 bytes in one 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");

Note : To add or add to the Jquery.validate.js file in the Additional-methods.js file. Recommendations are generally written in the Additional-methods.js file.

Note : add: Iszipcode: "Only Chinese characters, English letters, numbers, and underscores" are added in the Messages_cn.js file. Add a reference to the Additional-methods.js file before calling.

10. Verification of Radio and checkbox, select

Radio's required indicates that one must be selected.

<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 it 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 checks, rangelength:[2,3] indicates the number of bands selected.

<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 select indicates that 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 value= "3" >Oi</option></select>

The minlength of select indicates the minimum number selected (select with multiple selections), maxlength indicates the maximum number of checks, and rangelength:[2,3] indicates the number of bands to be selected.

<select id= "fruit" name= "fruit" title= "Please select at least-fruits" class= "{required:true, minlength:2}" Multipl E= "multiple" >    <option value= "B" >Banana</option>    <option value= "a" >apple</option >    <option value= "P" >Peach</option>    <option value= "T" >turtle</option></ Select>

JQuery Validate Content

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.