Latest web development tutorials

jQuery Validate

jQuery Validate plugin for forms authentication provides a powerful feature that allows client-side form validation easier, while providing plenty of customization options to meet application needs. The plug-in bundled with a useful set of validation methods, including URL and email authentication, while providing a user-defined method for the preparation of the API. All binding method using English as the default error message, and has been translated into 37 other languages.

The plug-in is written and maintained by the Jorn Zaefferer, he is a member of the jQuery team is lead developer of jQuery UI team is QUnit maintenance personnel. The plug-in 2006 jQuery early when it is already beginning to emerge, and has been updated since. The current version is 1.14.0.

Access jQuery Validate the official website to download the latest version of jQuery Validate plugin.

Version 1.14.0 Download this tutorial: http://static.w3big.com/download/jquery-validation-1.14.0.zip

Import js library (using this tutorial CDN)

<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

The default validation rules

No. rule description
1 required: true You must enter the field.
2 remote: "check.php" Using ajax method call check.php validate the input value.
3 email: true You must enter the correct e-mail format.
4 url: true You must enter the correct URL format.
5 date: true You must enter the correct date format. Ie6 date validation error caution.
6 dateISO: true You must enter the correct date format (ISO), for example: 2009-06-23,1998 / 01/22. Verifies only format that does not validate.
7 number: true You must enter a valid number (negative numbers, decimals).
8 digits: true You must enter an integer.
9 creditcard: You must enter a valid credit card number.
10 equalTo: "# field" Input values ​​must #field same.
11 accept: The input string has a legitimate extension (suffix upload files).
12 maxlength: 5 Maximum length of the input string 5 (Kanji count as one character).
13 minlength: 10 The minimum length of the input string is 10 (characters count as one character).
14 rangelength: [5,10] Length of the input string must be between 5 and 10. (a kanji character count).
15 range: [5,10] Enter the value must be between 5 and 10.
16 max: 5 Enter a value not greater than 5.
17 min: 10 Enter a value not less than 10.

Default Tips

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 tips Chinese information packet, located in the download package dist / localization / messages_zh.js, reads 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, 中文 (Zhongwé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 localize the information file dist / localization / messages_zh.js introduced to the page:

<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>

Use

1, the validation rules written control

<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.w3big.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></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"

2, the validation rules written 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: "请选择两个主题"
    }
});

messages at a control if there is no message, will use the default information

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

required: true value is a must.
required: "#aa: checked" is an expression of true, you need to verify.
required: function () {} return true, expressed the need for verification.

Two commonly used in the back, in the form need to fill or not fill elements.

Common methods and attention to issues

1, otherwise replace the default SUBMIT

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

Way to use ajax

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

You can set default values ​​validate worded as follows:

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

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

2, debug, verification is not only submit the form

If this parameter is true, then the form is not submitted, only checks carried out, it is very convenient when debugging.

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

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

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

3, ignore: ignore certain elements are not verified

ignore: ".ignore"

4. Change the location of the error message displayed

errorPlacement:Callback

Indicate the location of misplaced, the default is: error.appendTo (element.parent ()); that is the wrong message behind authentication element.

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

Examples

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

The role of the code is: Under normal circumstances the error message is displayed in the <td class = "status"> </ td> if the radio is displayed in the <td> </ td>, if the checkbox is displayed in the content of Behind.

参数 类型 描述 默认值
errorClass String 指定错误提示的 css 类名,可以自定义错误提示的样式。 "error"
errorElement String 用什么标签标记错误,默认是 label,可以改成 em。 "label"
errorContainer Selector 显示或者隐藏验证信息,可以自动实现有错误信息出现时把容器属性变为显示,无错误时隐藏,用处不大。
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector 把错误信息统一放在一个容器里面。
wrapper String 用什么标签再把上边的 errorELement 包起来。

Usually these three attributes simultaneously, to achieve display all error functions in a container, and no information is automatically hidden.

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

5, change the style of the error message displayed

Setting error of style, you can increase the icon is displayed, the system has established a validation.css, designed to maintain the style of the verification document.

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 verified by performing a function

 success: String, Callback 

To verify that the elements by the operation after the verification, if followed by a string that will be treated as a css class, but also 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 verify the elements defined in CSS style <style> label.valid {} </ style>.

success: "valid"

7, modify the trigger validation

Although the following is a boolean, but recommended unless you want to false, otherwise Freeze added.

触发方式 类型 描述 默认值
onsubmit Boolean 提交时验证。设置为 false 就用其他方法去验证。 true
onfocusout Boolean 失去焦点时验证(不包括复选框/单选按钮)。 true
onkeyup Boolean 在 keyup 时验证。 true
onclick Boolean 在点击复选框和单选按钮时验证。 true
focusInvalid Boolean 提交表单后,未通过验证的表单(第一个或提交之前获得焦点的未通过验证的表单)会获得焦点。 true
focusCleanup Boolean 如果是 true 那么当未通过验证的元素获得焦点时,移除错误提示。避免和 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

 remote: URL 

Way to authenticate using ajax, submitted to the current default value to a remote address verification, if required to submit other values, you can use the data option.

 remote: "check-email.php" 
remote: {
    url: "check-email.php", // Spooler type: "post", // data transmission mode dataType: "json", // receive data format data: {username // data to be passed: function ( ) {
            return $ ( "# username") val ().;
        }
    }
}

Remote address only output "true" or "false", can not have other output.

9, adding custom validation

 addMethod: name, method, message 

Custom authentication methods

// 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 that the value entered in {0} - {1} between bytes (one byte characters count 2)"));

// Postal code verification jQuery.validator.addMethod ( "isZipCode", function (value, element) {   
    var tel = / ^ [0-9] {6} $ /;
    return this.optional (element) || (tel.test (value));
} "Please fill in the correct your zip code");

Note: To add additional-methods.js file or add jquery.validate.js file.Recommendations generally written in additional-methods.js file.

Note: messages_cn.js file, add: isZipCode: "can include text, letters, numbers, and underscores."Before calling To add additional-methods.js file references.

10, radio and checkbox, select the verification

The radio must select a required representation.

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

checkbox must select the required representation.

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

represents the minimum number of minlength checkbox must be checked, maxlength represents the maximum number of selected, rangelength: [2,3] represents the number of the selected range.

<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 the required showing the selected value can not 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 the selected representation minlength minimum number of (multiple choice of select), maxlength represents the maximum number of selected, rangelength: [2,3] represents the number of the selected interval.

<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

名称 返回类型 描述
validate(options) Validator 验证所选的 FORM。
valid() Boolean 检查是否验证通过。
rules() Options 返回元素的验证规则。
rules("add",rules) Options 增加验证规则。
rules("remove",rules) Options 删除验证规则。
removeAttrs(attributes) Options 删除特殊属性并且返回它们。
自定义选择器
:blank Validator 没有值的筛选器。
:filled Array <Element> 有值的筛选器。
:unchecked Array <Element> 没选择的元素的筛选器。
实用工具
jQuery.format(template,argument,argumentN...) String 用参数代替模板中的 {n}。

Validator

validate method returns a Validator object. Validator object has many methods can be used to trigger the calibration procedure or change the contents of the form, several commonly used methods are listed below.

名称 返回类型 描述
form() Boolean 验证 form 返回成功还是失败。
element(element) Boolean 验证单个元素是成功还是失败。
resetForm() undefined 把前面验证的 FORM 恢复到验证前原来的状态。
showErrors(errors) undefined 显示特定的错误信息。
Validator 函数
setDefaults(defaults) undefined 改变默认的设置。
addMethod(name,method,message) undefined 添加一个新的验证方法。必须包括一个独一无二的名字,一个 JAVASCRIPT 的方法和一个默认的信息。
addClassRules(name,rules) undefined 增加组合验证类型,在一个类里面用多种验证方法时比较有用。
addClassRules(rules) undefined 增加组合验证类型,在一个类里面用多种验证方法时比较有用。这个是同时加多个验证方法。

Built-in authentication

名称 返回类型 描述
required() Boolean 必填验证元素。
required(dependency-expression) Boolean 必填元素依赖于表达式的结果。
required(dependency-callback) Boolean 必填元素依赖于回调函数的结果。
remote(url) Boolean 请求远程校验。url 通常是一个远程调用方法。
minlength(length) Boolean 设置最小长度。
maxlength(length) Boolean 设置最大长度。
rangelength(range) Boolean 设置一个长度范围 [min,max]。
min(value) Boolean 设置最小值。
max(value) Boolean 设置最大值。
email() Boolean 验证电子邮箱格式。
range(range) Boolean 设置值的范围。
url() Boolean 验证 URL 格式。
date() Boolean 验证日期格式(类似 30/30/2008 的格式,不验证日期准确性只验证格式)。
dateISO() Boolean 验证 ISO 类型的日期格式。
dateDE() Boolean 验证德式的日期格式(29.04.1994 或 1.1.2006)。
number() Boolean 验证十进制数字(包括小数的)。
digits() Boolean 验证整数。
creditcard() Boolean 验证信用卡号。
accept(extension) Boolean 验证相同后缀名的字符串。
equalTo(other) Boolean 验证两个输入框的内容是否相同。
phoneUS() Boolean 验证美式的电话号码。

validate () is optional

描述 代码
debug:进行调试模式(表单不提交)。
$(".selector").validate
({
	debug:true
})
把调试设置为默认。
$.validator.setDefaults({
	debug:true
})
submitHandler:通过验证后运行的函数,里面要加上表单提交的函数,否则表单不会提交。
$(".selector").validate({
	submitHandler:function(form) {
		$(form).ajaxSubmit();
	}
})
ignore:对某些元素不进行验证。
$("#myform").validate({
	ignore:".ignore"
})
rules:自定义规则,key:value 的形式,key 是要验证的元素,value 可以是字符串或对象。
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true
		}
	}
})
messages:自定义的提示信息,key:value 的形式,key 是要验证的元素,value 可以是字符串或函数。
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true
		}
	},
	messages:{
		name:"Name不能为空",
		email:{       
			required:"E-mail不能为空",
			email:"E-mail地址不正确"
		}
	}
})
groups:对一组元素的验证,用一个错误提示,用 errorPlacement 控制把出错信息放在哪里。
$("#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:类型 Boolean,默认 true,指定是否提交时验证。
$(".selector").validate({  
	onsubmit:false
})
onfocusout:类型 Boolean,默认 true,指定是否在获取焦点时验证。
$(".selector").validate({   
	onfocusout:false
})
onkeyup:类型 Boolean,默认 true,指定是否在敲击键盘时验证。
$(".selector").validate({
   onkeyup:false
})
onclick:类型 Boolean,默认 true,指定是否在鼠标点击时验证(一般验证 checkbox、radiobox)。
$(".selector").validate({
   onclick:false
})
focusInvalid:类型 Boolean,默认 true。提交表单后,未通过验证的表单(第一个或提交之前获得焦点的未通过验证的表单)会获得焦点。
$(".selector").validate({
   focusInvalid:false
})
focusCleanup:类型 Boolean,默认 false。当未通过验证的元素获得焦点时,移除错误提示(避免和 focusInvalid 一起使用)。
$(".selector").validate({
   focusCleanup:true
})
errorClass:类型 String,默认 "error"。指定错误提示的 css 类名,可以自定义错误提示的样式。
$(".selector").validate({ 
	errorClass:"invalid"
})
errorElement:类型 String,默认 "label"。指定使用什么标签标记错误。
$(".selector").validate
   errorElement:"em"
})
wrapper:类型 String,指定使用什么标签再把上边的 errorELement 包起来。
$(".selector").validate({
   wrapper:"li"
})
errorLabelContainer:类型 Selector,把错误信息统一放在一个容器里面。
$("#myform").validate({   
	errorLabelContainer:"#messageBox",
	wrapper:"li",
	submitHandler:function() { 
		alert("Submitted!") 
	}
})
showErrors:跟一个函数,可以显示总共有多少个未通过验证的元素。
$(".selector").validate({  
	showErrors:function(errorMap,errorList) {
        $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
		this.defaultShowErrors();
	}
})
errorPlacement:跟一个函数,可以自定义错误放到哪里。
$("#myform").validate({  
	errorPlacement:function(error,element) {  
		error.appendTo(element.parent("td").next("td"));
   },
   debug:true
})
success:要验证的元素通过验证后的动作,如果跟一个字符串,会当作一个 css 类,也可跟一个函数。
$("#myform").validate({        
	success:"valid",
        submitHandler:function() { 
			alert("Submitted!") 
		}
})
highlight:可以给未通过验证的元素加效果、闪烁等。

addMethod (name, method, message) method

Parameters name is the name of the add method.

Parameter method is a function that takes three parameters (value, element, param).
value is the value of the element, element is the element itself, param is the parameter.

We can use addMethod to add except the built-in authentication method Validation method. For example, there is a field, only to lose a letter, the range is af, 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;
	}
}, "Must be a letter, and af");

If there is a form field id = "username", written in the rules:

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

AddMethod first parameter is the name of the authentication method to add, then is af.
addMethod third parameter, a custom error message, suggesting here is: "must be a letter, and af".
addMethod second parameter is a function, this is more important, the wording of the decision to use this method of verification.

If only one parameter, write directly, such as af: "a", then this is a unique parameter, if more than one parameter is written in [], separated by commas.

meta String mode

$ ( "# 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>

Examples Demo

Fictional examples

Examples of real-world

Examples Download