JQuery Validate W3C content, jqueryvalidate

Source: Internet
Author: User
Tags valid email address

JQuery Validate W3C content, jqueryvalidate
Import js Library

<script src="../js/jquery.js" type="text/javascript"></script><script src="../js/jquery.validate.js" type="text/javascript"></script>
Default verification rules
Serial number Rules Description
1 Required: true Required Fields.
2 Remote: "check. php" Use the ajax method to call check. php to verify the input value.
3 Email: true You must enter an email 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 verification ie6 error, Use with caution.
6 DateISO: true You must enter a date (ISO) in the correct format, for example, 2009-06-23,1998/01/22. Only verify the format, not verify the validity.
7 Number: true You must enter a valid number (negative number, decimal number ).
8 Digits: true An integer is required.
9 Creditcard: You must enter a valid credit card number.
10 Failed 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: 5 A string with a maximum length of 5 characters ).
13 Minlength: 10 The input is a string of at least 10 characters ).
14 Rangelength: [5, 10] The input must be a string between 5 and 10 characters (one Chinese 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 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ü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.",    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}.")},

To modify the parameters, add the following to the js Code:

JQuery. extend (jQuery. validator. messages, {required: "required field", remote: "correct this field", email: "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 an integer can be entered ", creditcard:" enter a valid credit card number ", 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 to the page:

<script src="../js/messages_cn.js" type="text/javascript"></script>
Method 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> <label for = "email"> email </label> <input id = "email "name =" email "class =" required email "/> </p> <label for =" password "> Password </label> <input id =" password "name =" password "type =" password "class =" {required: true, minlength: 5} "/> </p> <label for =" confirm_password "> confirm the password </label> <input id =" confirm_password "name =" confirm_password "type = "password" class = "{required: true, minlength: 5, failed: '# password'} "/> </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. The Code is as follows:

2. Write validation rules to 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, failed to: "# password" }}, messages: {firstname: "Enter 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 widget 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> <label for = "email"> email </label> <input id = "email" name = "email "/> </p> <label for =" password "> Password </label> <input id =" password "name =" password "type =" password" /> </p> <label for = "confirm_password"> confirm the password </label> <input id = "confirm_password" name = "confirm_password" type = "password" /> </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, verification is required.
Required: function () {} returns true, indicating that verification is required.

The following two types of elements are commonly used: elements that need to be filled in or out of the form at the same time.

Common methods and precautions 1. use other methods to replace the default SUBMIT
$().ready(function() { $("#signupForm").validate({        submitHandler:function(form){            alert("submitted");               form.submit();        }        });});


 $(".selector").validate({      submitHandler: function(form)    {            $(form).ajaxSubmit();        }   }) 

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: only verify that the form is not submitted

If this parameter is set to true, the form is not submitted and only checked. This is very convenient for debugging.

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

If you want to set multiple forms to debug on a page, use:

$.validator.setDefaults({   debug: true})
3. ignore: ignore some elements and do not verify
ignore: ".ignore"
4. Change the location where the error message is displayed.

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


<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> <td>ParametersTypeDescriptionDefault ValueErrorClassStringSpecifies the css Class Name of the error message. You can customize the style of the error message."Error"ErrorElementStringLabel used to mark errors. The default value is label, which can be changed to em."Label"ErrorContainerSelectorDisplay or hide the verification information. The Container attribute can be automatically displayed when an error message is displayed, and hidden when no error occurs. This is of little use.
ErrorContainer: "# messageBox1, # messageBox2" ErrorLabelContainerSelectorPut the error information in a container. WrapperStringThe label used to pack the preceding errorELement. 

Generally, these three attributes are 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"
5. Change the display style of the error message.

Set the style of the error message. You can add an icon to display the error message. A validation.css file has been created in the system to maintain the style of the validation 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 passes the function verification.

If an element is followed by a string, it is 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 the style <style> label. valid {}</style> defined in CSS.

success: "valid"
7. Modify the trigger mode for verification

Although the following values are boolean, we recommend that you do not add them unless you change them to false.

Trigger Method Type Description Default Value
Onsubmit Boolean Verification upon submission. If it is set to false, use other methods for verification. True
Onfocusout Boolean Verification when the focus is lost (excluding check boxes/Single-choice buttons ). True
Onkeyup Boolean Verification during keyup. True
Onclick Boolean Verify when you click the check box and single-choice button. True
FocusInvalid Boolean 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) gets the focus. True
FocusCleanup Boolean If this parameter is set to true, the error message is removed when the unverified element gets the focus. Avoid using it 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 Verification

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 data format data: {// username: function () {return $ ("# username "). val ();}}}

The remote address can only output "true" or "false". No other output is allowed.

9. add custom Verification
addMethod:name, method, message

Custom Verification Method

// Two bytes of text in 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 (one text is counted as two bytes)"); // zip 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 ");

Note:: To add in the additional-methods.js file or in the jquery. validate. js file. It is recommended to write it in the additional-methods.js file.

Note:: In the messages_cn.js file, add isZipCode: "Only Chinese characters, English letters, numbers, and underscores are allowed ". Add a reference to the additional-methods.js file before calling.

10. radio, checkbox, and select Verification

Required of radio 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 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.