Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery Validate

jQuery Validate

The jQuery Validate plugin provides powerful validation for forms, making client-side form validation easier while offering a wealth of customization options to meet various application needs. The plugin bundles a set of useful validation methods, including URL and email validation, and provides an API for writing user-defined methods. All bundled methods use English as their default error messages, and have been translated into 37 other languages.

This plugin is written and maintained by Jörn Zaefferer, a member of the jQuery team, a lead developer of the jQuery UI team, and the maintainer of QUnit. The plugin first appeared in the early days of jQuery in 2006 and has been updated ever since. The current version is 1.14.0.

Access the jQuery Validate Official Site, download the latest version of the jQuery Validate plugin.

Import the JS library (using the CDN provided by ByteDance)







Default Validation Rules

No. Rule Description
1 required:true A field that must be entered.
2 remote:"check.php" Use the ajax method to call check.php to validate the input value.
3 email:true Must enter a correctly formatted email address.
4 url:true Must enter a correctly formatted URL.
5 date:true Must enter a correctly formatted date. Date validation has issues in IE6, so use with caution.
6 dateISO:true Must enter a correctly formatted date (ISO), for example: 2009-06-23, 1998/01/22. Only the format is validated, not the validity.
7 number:true Must enter a valid number (negative numbers, decimals).
8 digits:true Must enter an integer.
9 creditcard: 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 extension (the suffix of an uploaded file).
12 maxlength:5 Enter a string with a maximum length of 5 (a Chinese character counts as one character).
13 minlength:10 Enter a string with a minimum length of 10 (a Chinese character counts as one character).
14 rangelength:[5,10] Enter a string whose length must be between 5 and 10 (a Chinese character counts 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 Messages



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 ).",

    number: "Please enter a valid number.",

    digits: "Please enter only digits.",

    creditcard: "Please enter a valid credit card number.",

    equalTo: "Please enter the same value again.",

    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}." )

}

jQuery Validate provides a Chinese message pack, located at dist/localization/messages_zh.js in the download package, with the following content:



(function( factory ) {

    if ( typeof define === "function" && define.amd ) {

        define( ["jquery", "../jquery.validate"], factory );

    } else {

        factory( jQuery );

    }

}(function( $ ) {



/*

 * Translated default messages for the jQuery validation plugin.

 * Locale: ZH (Chinese, Chinese (Zhōngwén), Chinese, Hanzi)

 */

$.extend($.validator.messages, {

    required: "这是必填字段",

    remote: "请修正此字段",

    email: "请输入有效的电子邮件地址",

    url: "请输入有效的网址",

    date: "请输入有效的日期",

    dateISO: "请输入有效的日期 (YYYY-MM-DD)",

    number: "请输入有效的数字",

    digits: "只能输入数字",

    creditcard: "请输入有效的信用卡号码",

    equalTo: "你的输入不相同",

    extension: "请输入有效的后缀",

    maxlength: $.validator.format("最多可以输入 {0} 个字符"),

    minlength: $.validator.format("最少要输入 {0} 个字符"),

    rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),

    range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),

    max: $.validator.format("请输入不大于 {0} 的数值"),

    min: $.validator.format("请输入不小于 {0} 的数值")

});



}));

You can include the localization file dist/localization/messages_zh.js in your page:



    

Usage

1. Write validation rules into the controls







    







输入您的名字,邮箱,URL,备注。

Try it »

2. Write validation rules into the JS code



$().ready(function() {

// Validate the submission form after key press, release, and submission

  $("#signupForm").validate({

    rules: {

      firstname: "required",

      lastname: "required",

      username: {

        required: true,

        minlength: 2

      },

      password: {

        required: true,

        minlength: 5

      },

      confirm_password: {

        required: true,

        minlength: 5,

        equalTo: "#password"

      },

      email: {

        required: true,

        email: true

      },

      topic: {

        required: "#newsletter:checked",

        minlength: 2

      },

      agree: "required"

    },

    messages: {

      firstname: "请输入您的名字",

      lastname: "请输入您的姓氏",

      username: {

        required: "请输入用户名",

        minlength: "用户名必需由两个字符组成"

      },

      password: {

        required: "请输入密码",

        minlength: "密码长度不能小于 5 个字符"

      },

      confirm_password: {

        required: "请输入密码",

        minlength: "密码长度不能小于 5 个字符",

        equalTo: "两次密码输入不一致"

      },

      email: "请输入一个正确的邮箱",

      agree: "请接受我们的声明",

      topic: "请选择两个主题"

     }

    })

});

In messages, if a control has no message, the default message will be used



验证完整的表单

主题 (至少选择两个) - 注意:如果没有勾选“我乐意接收新信息”以下选项会隐藏,但我们这里作为演示让它可见

Try it »

required: true The value is required.
required: "#aa:checked" If the expression evaluates to true, validation is required.
required: function(){} Returning true indicates that validation is required.

The last two are commonly used for elements in a form that must be filled in or left blank together.

Common Methods and Notes

1. Replace the Default SUBMIT with Another Method



$().ready(function() {

 $("#signupForm").validate({

        submitHandler:function(form){

            alert("提交事件!");   

            form.submit();

        }    

    });

});

Using the ajax method



 $(".selector").validate({     

 submitHandler: function(form) 

   {      

      $(form).ajaxSubmit();     

   }  

 }) 

You can set the default values for validate as follows:



$.validator.setDefaults({

  submitHandler: function(form) { alert("提交事件!");form.submit(); }

});

If you want to submit the form, use form.submit() rather than $(form).submit().

2. debug - Validate Only, Do Not Submit the Form

If this parameter is true, the form will not be submitted; only checks are performed, which is very convenient for debugging.



$().ready(function() {

 $("#signupForm").validate({

        debug:true

    });

});

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



$.validator.setDefaults({

   debug: true

})

3. ignore: Ignore Certain Elements During Validation



ignore: ".ignore"

4. Change the Display Position of Error Messages



errorPlacement:Callback

Specifies where the error is placed. By default: error.appendTo(element.parent()); that is, the error message is placed after the validated element.



errorPlacement: function(error, element) {  

    error.appendTo(element.parent());  

}

Example



将错误信息放在 label 元素后并使用 span 元素包裹它

Login Form

Try it »

The code works as follows: in general, the error message is displayed in a label; for radio it is displayed in a label, and for checkbox it is displayed after the content.

Parameters Type Description Default value
errorClass String Specifies the CSS class name for error messages, allowing you to customize their style. "error"
errorElement String Specifies which tag marks errors; the default is label, which can be changed to em. "label"
errorContainer Selector Show or hide validation messages; it can automatically change the container's display property to show when error messages appear and hide when there are none. It is of limited use.
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector Put all error messages together in one container.
wrapper String Specifies which tag wraps the errorElement above.

Typically these three properties are used together to display all error messages within one container and hide it automatically when there are no messages.



errorContainer: "div.error",

errorLabelContainer: $("#signupForm div.error"),

wrapper: "li"

5. Change the Display Style of Error Messages

Set the style of error messages; you can add icons. This system has created a validation.css file specifically for maintaining the styles of validation files.



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. Execute a Function When Each Field Passes Validation

success:String,Callback

The action taken after the validated element passes validation. If followed by a string, it is treated as a CSS class; it can also be followed by a function.



success: function(label) {

    // set   as text for IE

    label.html(" ").addClass("checked");

    //label.addClass("valid").text("Ok!")

}

Adds "valid" to the validated element, with the style defined in CSS .



success: "valid"

7. Change the Validation Trigger Method

Although the following are of boolean type, it is recommended not to add them arbitrarily unless you want to change them to false.

Trigger Method Type Description Default value
onsubmit Boolean Validate on submit. If set to false, use other methods to validate. true
onfocusout Boolean Validate when the field loses focus (excluding checkboxes/radio buttons). true
onkeyup Boolean Validate on keyup. true
onclick Boolean Validate when checkboxes and radio buttons are clicked. true
focusInvalid Boolean After submitting the form, the form that failed validation (the first invalid form, or the invalid form that had focus before submission) will receive focus. true
focusCleanup Boolean If true, error messages are removed when an invalid element receives focus. Avoid using it together with focusInvalid. false


// Reset form

$().ready(function() {

 var validator = $("#signupForm").validate({

        submitHandler:function(form){

            alert("submitted");   

            form.submit();

        }    

    });

    $("#reset").click(function() {

        validator.resetForm();

    });



});

8. Asynchronous Validation

remote:URL

When validating via ajax, the current value being validated 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",     //后台处理程序

    type: "post",               //数据发送方式

    dataType: "json",           //接受数据格式   

    data: {                     //要传递的数据

        username: function() {

            return $("#username").val();

        }

    }

}

The remote address can only output "true" or "false", with no other output.

9. Add Custom Validation

addMethod:name, method, message

Custom Validation Methods



// Two bytes of 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("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));



// 邮政编码验证   

jQuery.validator.addMethod("isZipCode", function(value, element) {   

    var tel = /^[0-9]{6}$/;

    return this.optional(element) || (tel.test(value));

}, "请正确填写您的邮政编码");

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

Note: Add in the messages_cn.js file: isZipCode: "can only contain Chinese characters, English letters, numbers, and underscores". Before calling, add a reference to the additional-methods.js file.

10. Validation of radio, checkbox, and select

For radio, required means one option must be selected.







For checkbox, required means it must be checked.





For checkbox, minlength indicates the minimum number that must be checked, maxlength indicates the maximum number, and rangelength:[2,3] indicates the range of the number to be checked.









For select, required means the selected value cannot be empty.





For select, minlength indicates the minimum number selected (for a multi-select), maxlength indicates the maximum number, and rangelength:[2,3] indicates the range of the number selected.





jQuery.validate Chinese API

Name Return Type Description
validate(options) Validator Validate the selected FORM.
valid() Boolean Check whether validation passed.
rules() Options Return the validation rules of an element.
rules("add",rules) Options Add validation rules.
rules("remove",rules) Options Remove validation rules.
removeAttrs(attributes) Options Remove special attributes and return them.
Custom Selectors
:blank Validator Filters without values.
:filled Array Filters with values.
:unchecked Array Filters for elements that are not selected.
Utility functions
jQuery.format(template,argument,argumentN...) String Replace {n} in the template with a parameter.

Validator

The validate method returns a Validator object. The Validator object has many methods that can trigger the validation process or change the content of the form; several commonly used methods are listed below.

Name Return Type Description
form() Boolean Validate the form and return success or failure.
element(element) Boolean Validate a single element and return success or failure.
resetForm() undefined Restore the previously validated FORM to its original state before validation.
showErrors(errors) undefined Display specific error messages.
Validator Functions
setDefaults(defaults) undefined Change the default settings.
addMethod(name,method,message) undefined Add a new validation method. It must include a unique name, a JavaScript method, and a default message.
addClassRules(name,rules) undefined Add a composite validation type, useful when using multiple validation methods in one class.
addClassRules(rules) undefined Add a composite validation type, useful when using multiple validation methods in one class. This adds multiple validation methods at the same time.

Built-in Validation Methods

Name Return Type Description
required() Boolean Required validation element.
required(dependency-expression) Boolean Required element depends on the result of an expression.
required(dependency-callback) Boolean Required element depends on the result of a callback function.
remote(url) Boolean Request remote validation. The url is usually a remote call method.
minlength(length) Boolean Set the minimum length.
maxlength(length) Boolean Set the maximum length.
rangelength(range) Boolean Set a length range [min,max].
min(value) Boolean Set the minimum value.
max(value) Boolean Set the maximum value.
email() Boolean Validate email format.
range(range) Boolean Set the range of values.
url() Boolean Validate URL format.
date() Boolean Validate date format (a format like 30/30/2008; only the format is validated, not the date's accuracy).
dateISO() Boolean Validate ISO date format.
dateDE() Boolean Validate German date format (29.04.1994 or 1.1.2006).
number() Boolean Validate decimal numbers (including those with decimals).
digits() Boolean Validate integers.
creditcard() Boolean Validate credit card numbers.
accept(extension) Boolean Validate strings with the same suffix.
equalTo(other) Boolean Validate whether the contents of two input boxes are the same.
phoneUS() Boolean Validate US-style phone numbers.

validate() Options

Description Code
debug: Enable debug mode (the form is not submitted).

$(".selector").validate ({ debug:true }) | | Set debugging as the default. |

$.validator.setDefaults({

    debug:true

})

| | submitHandler: The function run after validation passes; it must include the form submission function, otherwise the form will not be submitted. |
$(".selector").validate({

    submitHandler:function(form) {

        $(form).ajaxSubmit();

    }

})

| | ignore: Do not validate certain elements. |
$("#myform").validate({

    ignore:".ignore"

})

| | rules: Custom rules in key:value form, where key is the element to validate and value can be a string or object. |
$(".selector").validate({

    rules:{

        name:"required",

        email:{

            required:true,

            email:true

        }

    }

})

| | messages: Custom messages in key:value form, where key is the element to validate and value can be a string or function. |
$(".selector").validate({

    rules:{

        name:"required",

        email:{

            required:true,

            email:true

        }

    },

    messages:{

        name:"Name不能为空",

        email:{
            required:"E-mail不能为空",             email:"E-mail地址不正确"         }     } })
| | groups: Validate a group of elements with a single error message; use errorPlacement to control where the error is placed. |
$("#myform").validate({

    groups:{

        username:"fname

        lname"

    },

    errorPlacement:function(error,element) {

        if (element.attr("name") == "fname" || element.attr("name") == "lname")
            error.insertAfter("#lastname");         else
            error.insertAfter(element);     }, debug:true })
| | OnSubmit: Type Boolean, default true, specifies whether to validate on submit. |
$(".selector").validate({
    onsubmit:false })
| | onfocusout: Type Boolean, default true, specifies whether to validate when focus is gained. |
$(".selector").validate({
    onfocusout:false })
| | onkeyup: Type Boolean, default true, specifies whether to validate on keyup. |
$(".selector").validate({

onkeyup:false

})

| | onclick: Type Boolean, default true, specifies whether to validate on mouse click (generally for checkbox and radiobox). |
$(".selector").validate({

onclick:false

})

| | focusInvalid: Type Boolean, default true. After submitting the form, the form that failed validation (the first invalid form, or the invalid form that had focus before submission) will receive focus. |
$(".selector").validate({

focusInvalid:false

})

| | focusCleanup: Type Boolean, default false. When an invalid element receives focus, remove the error message (avoid using it together with focusInvalid). |
$(".selector").validate({

focusCleanup:true

})

| | errorClass: Type String, default "error". Specifies the CSS class name for error messages, allowing you to customize their style. |
$(".selector").validate({

    errorClass:"invalid"

})

| | errorElement: Type String, default "label". Specifies which tag is used to mark errors. |
$(".selector").validate

errorElement:"em"

})

| | wrapper: Type String, specifies which tag wraps the errorElement above. |
$(".selector").validate({

wrapper:"li"

})

| | errorLabelContainer: Type Selector, puts all error messages together in one container. |
$("#myform").validate({
    errorLabelContainer:"#messageBox",     wrapper:"li",     submitHandler:function() {         alert("Submitted!")     } })
| | showErrors: Followed by a function that can show how many elements in total failed validation. |
$(".selector").validate({
    showErrors:function(errorMap,errorList) { $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");         this.defaultShowErrors();     } })
| | errorPlacement: Followed by a function that lets you customize where errors are placed. |
$("#myform").validate({
    errorPlacement:function(error,element) {
        error.appendTo(element.parent("td").next("td")); }, debug:true })
| | success: The action taken after the validated element passes validation; if followed by a string, it is treated as a CSS class, and it can also be followed by a function. |
$("#myform").validate({
    success:"valid", submitHandler:function() {             alert("Submitted!")         } })
| | highlight: Can add effects, flashing, etc. to elements that fail validation. | |

The addMethod(name,method,message) Method

The name parameter is the name of the method being added.

The method parameter is a function that receives three parameters (value, element, param).
value is the element's value, element is the element itself, and param is the parameter.

We can use addMethod to add validation methods beyond the built-in Validation methods. For example, a field that accepts only a single letter in the range a-f can be written as follows:



$.validator.addMethod("af",function(value,element,params){  

    if(value.length>1){

        return false;

    }

    if(value>=params[0] && value<=params[1]){

        return true;

    }else{

        return false;

    }

},"必须是一个字母,且a-f");

If a form field has name="username", then write in rules:



username:{

   af:["a","f"]

}

The first parameter of addMethod is the name of the validation method being added, which here is af.
The third parameter of addMethod is the custom error message; here the message is: "must be a single letter, and a-f".
The second parameter of addMethod is a function, which is important because it determines how the validation method is written.

If there is only one parameter, write it directly, for example af:"a", where a is the only parameter. If there are multiple parameters, write them in [] separated by commas.

meta String Approach



$("#myform").validate({



   meta:"validate",



   submitHandler:function() { 

alert("Submitted!") }



})











Example Download

Complete code:

Downloading

.