Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery Validate


May 07, 2021 jQuery


Table of contents


jQuery Validate

The jQuery Validate plug-in provides forms with powerful validation capabilities that make client form validation easier, while providing a wide range of customization options to meet the needs of your application. T he plug-in bundles a useful set of validation methods, including URL and email validation, while providing an API for writing user-defined methods. All bundling methods use English as an error message by default and have been translated into 37 other languages.

The plug-in was written and maintained by Jörn Zaeffer, a member of the jQuery team, a leading developer on the jQuery UI team, and a maintenance staff at QUnit. T he plug-in has been in the early days of jQuery since 2006 and has been updated to this day. The current version is 1.14.0.

Visit jQuery Validate's website to download the latest version of the jQuery Validate plug-in.

Version 1.14.0 recommended for the w3cschool online tutorial download address: http://libs.cdnjs.net/jquery-validate/1.14.0/

Import js library (CDN recommended using w3cschool online tutorial)

<script src="http://libs.cdnjs.net/jquery/2.2.1/jquery.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/jquery.validate.min.js" rel="external nofollow"  rel="external nofollow" ></script>

The default check rule

Serial number Rules Describe
1 required:true The field that must be entered.
2 remote:"check.php" Use the ajax method to call .php verify the input value.
3 email:true You must enter an e-mail message in the correct format.
4 url:true You must enter the 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 Dates (ISOs) in the correct format must be entered, e.g. 2009-06-23, 1998/01/22. Only the format is validated, not the validity.
7 number:true Legitimate numbers (negative, small) must be entered.
8 digits:true An integer must be entered.
9 creditcard: A legitimate credit card number must be entered.
10 equalTo:"#field" The input value must be the same #field the same.
11 accept: Enter a string with a legitimate suffix name (the suffix of the upload file).
12 maxlength:5 Enter strings up to 5 in length (Chinese characters count as one character).
13 minlength:10 Enter a string with a minimum length of 10 (Chinese characters count as one character).
14 rangelength:[5,10] The input must be a string between 5 and 10 in length (Chinese characters count 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.

The 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 ).",
    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 Chinese information tip pack at the /localization/messages_zh.js package, as follows:

(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, 中文 (Zhōngwén), 汉语, 漢語)
 */
$.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 introduce the localized information file /localization/messages_zh.js to the page:

<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/localization/messages_zh.js" rel="external nofollow"  rel="external nofollow" ></script>

How to use it

1, the check rules are written to the control

<script src="http://libs.cdnjs.net/jquery/2.2.1/jquery.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/jquery.validate.min.js" rel="external nofollow"  rel="external nofollow" ></script>
<script src="http://libs.cdnjs.net/jquery-validate/1.14.0/localization/messages_zh.js" rel="external nofollow"  rel="external nofollow" ></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().ready(function() {
    $("#commentForm").validate();
});
</script>

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>输入您的名字,邮箱,URL,备注。</legend>
    <p>
      <label for="cname">Name (必需, 最小两个字母)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (必需)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (可选)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">备注 (必需)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>

Try it out . . .

2, the check rules are written to the js code

$().ready(function() {
// 在键盘按下并释放及提交后验证提交表单
  $("#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: "请选择两个主题"
     }
    })
});

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

<form class="cmxform" id="signupForm" method="get" action="">
  <fieldset>
    <legend>验证完整的表单</legend>
    <p>
      <label for="firstname">名字</label>
      <input id="firstname" name="firstname" type="text">
    </p>
    <p>
      <label for="lastname">姓氏</label>
      <input id="lastname" name="lastname" type="text">
    </p>
    <p>
      <label for="username">用户名</label>
      <input id="username" name="username" type="text">
    </p>
    <p>
      <label for="password">密码</label>
      <input id="password" name="password" type="password">
    </p>
    <p>
      <label for="confirm_password">验证密码</label>
      <input id="confirm_password" name="confirm_password" type="password">
    </p>
    <p>
      <label for="email">Email</label>
      <input id="email" name="email" type="email">
    </p>
    <p>
      <label for="agree">请同意我们的声明</label>
      <input type="checkbox" class="checkbox" id="agree" name="agree">
    </p>
    <p>
      <label for="newsletter">我乐意接收新信息</label>
      <input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
    </p>
    <fieldset id="newsletter_topics">
      <legend>主题 (至少选择两个) - 注意:如果没有勾选“我乐意接收新信息”以下选项会隐藏,但我们这里作为演示让它可见</legend>
      <label for="topic_marketflash">
        <input type="checkbox" id="topic_marketflash" value="marketflash" name="topic">Marketflash
      </label>
      <label for="topic_fuzz">
        <input type="checkbox" id="topic_fuzz" value="fuzz" name="topic">Latest fuzz
      </label>
      <label for="topic_digester">
        <input type="checkbox" id="topic_digester" value="digester" name="topic">Mailing list digester
      </label>
      <label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
    </fieldset>
    <p>
      <input class="submit" type="submit" value="提交">
    </p>
  </fieldset>
</form>

Try it out . . .

Needed: True values are required.
Needed: The value #aa "Checked" expression is true and needs to be verified.
Required: function() is returned as true, indicating that verification is required.

The back two are commonly used, and elements in the form that need to be filled in or not filled in at the same time.

Common methods and attention to problems

1. Replace the default SUBMIT by other means

$().ready(function() {
 $("#signupForm").validate({
        submitHandler:function(form){
            alert("提交事件!");   
            form.submit();
        }    
    });
});

Use the ajax method

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

You can set the default value for validate, as follows:

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

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

2, debug, only verify not to submit the form

If this parameter is true, the form is not submitted, only checked, and debugging is convenient.

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

If there are multiple forms on a page that want to be set up as debugs, use:

$.validator.setDefaults({
   debug: true
})

3, ignore: ignore some elements do not validate

ignore: ".ignore"

4. Change where the error message is displayed

errorPlacement:Callback

Indicates the location of the wrong placement, the default is: error.appendTo (element.parent()); That is, put the error message after the validated element.

errorPlacement: function(error, element) {  
    error.appendTo(element.parent());  
}

Instance

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

<form method="get" class="cmxform" id="form1" action="">
  <fieldset>
    <legend>Login Form</legend>
    <p>
      <label for="user">Username</label>
      <input id="user" name="user" required minlength="3">
    </p>
    <p>
      <label for="password">Password</label>
      <input id="password" type="password" maxlength="12" name="password" required minlength="5">
    </p>
    <p>
      <input class="submit" type="submit" value="Login">
    </p>
  </fieldset>
</form>

Try it out . . .

The effect of the code is to generally display the error message in the "status" of the slt;td class, or in the case of radio, in the case of the radio, in the case of the checkbox, in the case of the content.

parameter type describe Defaults
errorClass String Specify the CSS class name of the error prompt to customize the style of the error prompt. "error"
errorElement String What tag marker is used, the default is Label, it can be changed to EM. "label"
errorContainer Selector Show or hide the verification information, you can automatically implement the error message to display when the error message appears, hidden when there is no error, and is not large.
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector Unify the error message in a container.
wrapper String What tag uses the Errorelement on the upper side.

Typically, these three properties are used at the same time, implementing the ability to display all error prompts in a container and automatically hide them when there is no information.

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

5, change the style of the error message display

By styled the error prompt, you can add an icon display, and a validation .css has been established in the system to maintain the style of the check 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 validation through the execution function


The action of the element to be validated, if followed by a string, is treated 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 CSS.

success: "valid"

7, verification of the trigger method modification

Although the following is boolean type, it is recommended that you do not add it indiscriminately unless you want to change it to false.

Trigger type describe Defaults
onsubmit Boolean Verify when submitting.Set to False to verify using other methods. true
onfocusout Boolean Verify when you lose focus (do not include check box / radio button). true
onkeyup Boolean Verify at Keyup. true
onclick Boolean Verify when you click the check box and the radio button. true
focusInvalid Boolean After submitting the form, the focus will be obtained without the verification form (the first or promptable form before the focus is obtained) will be focused. true
focusCleanup Boolean If you are TRUE, then the error prompt is removed when the focus is not passed through the validated element.Avoid use with FocusInvalid. false


// 重置表单
$().ready(function() {
 var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
    $("#reset").click(function() {
        validator.resetForm();
    });

});


8, asynchronous verification

remoteURL

Using ajax for validation, the currently validated value is submitted to the remote address by default, and the data option is available if additional values need to be submitted.

remote: "check-email.php"
remote: {
    url: "check-email.php",     //后台处理程序
    type: "post",               //数据发送方式
    dataType: "json",           //接受数据格式   
    data: {                     //要传递的数据
        username: function() {
            return $("#username").val();
        }
    }
}

    

Remote addresses can only output "true" or "false" and cannot have other output.

9, add custom checks

addMethodname, method, message

Custom validation methods

// 中文字两个字节
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: To add in .js file or in the jquery.validate .js file. It is recommended that you generally write in the additional-.js file.

Note: Add messages_cn.js file: isZipCode: "Only Chinese, english letters, numbers, and underscores." Add a reference to the .js file before calling.

10, radio and checkbox, select verification

Radio's required means that one must be selected.

<input  type="radio" id="gender_male" value="m" name="gender" required />
<input  type="radio" id="gender_female" value="f" name="gender"/>

The required of the checkbox means that it must be selected.

<input type="checkbox" class="checkbox" id="agree" name="agree" required />

The minlength of the checkbox represents the minimum number that must be selected, maxlength represents the maximum number of selected numbers, and rangelength: .2,3) indicates the number interval that must be selected.

<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required 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's required means that the value selected cannot be empty.

<select id="jungle" name="jungle" title="Please select something!" required>
    <option value=""></option>
    <option value="1">Buga</option>
    <option value="2">Baga</option>
    <option value="3">Oi</option>
</select>

Select's minlength represents the minimum number selected (multi-select), maxlength represents the maximum number of selected numbers, and rangelength: .

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

jQuery.validate Chinese API

name Return type describe
validate(options) Validator Verify the selected form.
valid() Boolean Check if verification is passed.
rules() Options Returns the verification rules for the elements.
rules("add",rules) Options Increase verification rules.
rules("remove",rules) Options Delete the verification rule.
removeAttrs(attributes) Options Delete special properties and returns them.
Custom selector
:blank Validator No value of filters.
:filled Array <Element> Valosible filter.
:unchecked Array <Element> Filter for the elements that have not been selected.
Utilities
jQuery.format(template,argument,argumentN...) String Use parameters instead of {n} in the template.

Validator

The validate method returns a Validator object. Validator objects have many ways to raise a checker or change the contents of a form, and here are a few common methods.

name Return type describe
form() Boolean Verify that Form returns success or fail.
element(element) Boolean Verify that a single element is successful or failed.
resetForm() undefined Restore the previously verified FORM to the original state of the verification.
showErrors(errors) undefined Display specific error messages.
Validator function
setDefaults(defaults) undefined Change the default settings.
addMethod(name,method,message) undefined Add a new verification method.Must include a unique name, a method of javaScript and a default information.
addClassRules(name,rules) undefined Add a combined verification type, which is more useful when using multiple authentication methods in a class.
addClassRules(rules) undefined Add a combined verification type, which is more useful when using multiple authentication methods in a class.This is a plurality of verification methods at the same time.

Built-in verification

name Return type describe
required() Boolean Required to fill the verification element.
required(dependency-expression) Boolean The required elements depend on the results of the expression.
required(dependency-callback) Boolean The required elements depend on the result of the callback function.
remote(url) Boolean Request a remote check.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 Verify the email format.
range(range) Boolean Set the range of values.
url() Boolean Verify the URL format.
date() Boolean Verify the date format (similar to 30/30/2008 format, do not verify the date accuracy only verification format).
dateISO() Boolean Verify the date format of the ISO type.
dateDE() Boolean Verify German Date Format (29.04.1994 or 1.1.2006).
number() Boolean Verify that decimal numbers (including decimal).
digits() Boolean Verify integers.
creditcard() Boolean Verify the credit card number.
accept(extension) Boolean Verify the string of the same reachaes.
equalTo(other) Boolean Verify that the contents of the two input boxes are the same.
phoneUS() Boolean Verify American phone numbers.

The option of validate().

describe Code
Debug: Perform debug mode (form is not submitted).
$(".selector").validate
({
    debug:true
})
Set the debug set as default.
$.validator.setDefaults({
    debug:true
})
SubmitHandler: By verifying the function running, add a function committed by adding a form, otherwise the form will not be submitted.
$(".selector").validate({
    submitHandler:function(form) {
        $(form).ajaxSubmit();
    }
})
Ignore: Do not verify certain elements.
$("#myform").validate({
    ignore:".ignore"
})
Rules: Custom Rules, Key: Value form, Key is the element to verify, VALUE can be a string or object.
$(".selector").validate({
    rules:{
        name:"required",
        email:{
            required:true,
            email:true
        }
    }
})
Messages: Customized prompt information, key: value, key is the element to verify, 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: Verification of a set of elements, with an error message, where the error information is placed with ERRORPLACEMENT control.
$("#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, specify whether it is submitted to verify.
$(".selector").validate({  
    onsubmit:false
})
ONFOCUSOUT: Type Boolean, default true, specify whether it is verified when it is acquired.
$(".selector").validate({   
    onfocusout:false
})
Onkeyup: Type Boolean, Default True, specify whether it is verified when tap the keyboard.
$(".selector").validate({
   onkeyup:false
})
OnClick: Type Boolean, default true, specify whether it is verified when you click on the mouse (General Checkbox, Radiobox).
$(".selector").validate({
   onclick:false
})
FocusInvalid: Type Boolean, default true.After submitting the form, the focus will be obtained without the verification form (the first or promptable form before the focus is obtained) will be focused.
$(".selector").validate({
   focusInvalid:false
})
Focuscleanup: Type Boolean, default false.When the focus is not obtained by the validated element, the error message (avoiding the use of FocusInvalid).
$(".selector").validate({
   focusCleanup:true
})
ERRORCLASS: Type String, default "error".Specify the CSS class name of the error prompt to customize the style of the error prompt.
$(".selector").validate({ 
    errorClass:"invalid"
})
ErrorElement: Type String, default "label".Specifies what tag tag error is used.
$(".selector").validate
   errorElement:"em"
})
Wrapper: Type String, specify what tag is using the label and put it on the ErrorElement.
$(".selector").validate({
   wrapper:"li"
})
ERRORLABELCONTAINER: Type Selector, put the error message in one container.
$("#myform").validate({   
    errorLabelContainer:"#messageBox",
    wrapper:"li",
    submitHandler:function() { 
        alert("Submitted!") 
    }
})
SHOWERRORS: With a function, you can display a total of how many elements that are not passed through verification.
$(".selector").validate({  
    showErrors:function(errorMap,errorList) {
        $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
        this.defaultShowErrors();
    }
})
ERRORPLACEMENT: Follow with a function, where you can customize the error.
$("#myform").validate({  
    errorPlacement:function(error,element) {  
        error.appendTo(element.parent("td").next("td"));
   },
   debug:true
})
SUCCESS: The elements you want to verify can be followed by verifying, if you follow a string, you will be as a CSS class, or you can follow a function.
$("#myform").validate({        
    success:"valid",
        submitHandler:function() { 
            alert("Submitted!") 
        }
})
Highlight: You can add effect, flicker, etc. without passing the validated element.

AddMethod (name, method, message) method

The argument name is the name of the added method.

The argument method is a function that receives three arguments (value, element, param).
Value is the value of the element, element is the element itself, and param is the argument.

We can use addMethod to add validation methods in addition to the built-in Validation method. For example, there is a field that can only lose one letter, the range is a-f, 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 there is a form field with the name "username", write it in rules:

username:{
   af:["a","f"]
}

The first argument of addMethod is the name of the added validation method, which is af.
AddMethod's third argument is a custom error prompt, where the prompt is: "Must be a letter, and a-f".
AddMethod's second argument, which is a function, is important in determining how this validation method is written.

If there is only one argument, write directly, such as af:a", then a is the only parameter, and if there are more than one argument, write it in .

Meta String way

$("#myform").validate({

   meta:"validate",

   submitHandler:function() { 
alert("Submitted!") }

})
<script type="text/javascript" 
src="js/jquery.metadata.js"></script>

<script type="text/javascript" 
src="js/jquery.validate.js"></script>

<form id="myform">

  <input type="text" 
name="email" class="{validate:{ required:true,email:true }}" />

  <input type="submit" 
value="Submit" />

</form>

Example demonstration

A fictitious example

Real-world examples