jQuery Validat...LOGIN

jQuery Validate

jQuery Validate

The jQuery Validate plug-in provides powerful validation functions for forms, making client-side form validation easier and providing a large number 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 for error messages by default 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 on the jQuery UI team, and the maintainer of QUnit. This plugin has been around since the early days of jQuery in 2006 and has been updated ever since. The current version is 1.14.0.

Visit the jQuery Validate official website and download the latest version of the jQuery Validate plug-in.

Import js library

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

Default verification rules

Serial numberRulesDescription
1required:trueRequired fields.
2remote:"check.php"Use the ajax method to call check.php to verify the input value.
3email:trueA correctly formatted email must be entered.
4url:trueYou must enter the URL in the correct format.
5date:trueThe date must be entered in the correct format. Date verification ie6 error, use with caution.
6dateISO:trueThe date (ISO) in the correct format must be entered, for example: 2009-06-23, 1998/01/ twenty two. Only the format is verified, not the validity.
7number:trueMust enter a legal number (negative number, decimal).
8digits:trueMust enter an integer.
9creditcard:Must enter a legal credit card number.
10equalTo:"#field"The input value must be the same as #field.
11accept:Enter a string with a legal suffix (the suffix of the uploaded file).
12maxlength:5Enter a string with a maximum length of 5 (Chinese characters count as one character).
13minlength:10Enter a string with a minimum length of 10 (Chinese characters count as one character).
14rangelength:[5,10]The input length must be between 5 and 10 (Chinese characters count as one character ).
15range:[5,10]The input value must be between 5 and 10.
16max:5The input value cannot be greater than 5.
17min:10The 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 ).",
	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 prompt package, which is located in dist/localization/messages_zh.js of the download package. The content is 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 localize the message The file dist/localization/messages_zh.js is introduced to the page:

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

Usage method

1. Write the verification rules into the control

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP中文网(php.cn)</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().ready(function() {
    $("#commentForm").validate();
});
</script>
<style>
.error{
	color:red;
}
</style>
</head>
<body>
<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>
</body>
</html>

Try it

2. Write the verification rules into the js code at

$().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. If a control does not have a message, the default message will be called

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP中文网(php.cn)</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().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: "请选择两个主题"
	   }
	});
});
</script>
<style>
.error{
	color:red;
}
</style>
</head>
<body>
<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" style="display:none">至少选择两个</label>
    </fieldset>
    <p>
      <input class="submit" type="submit" value="提交">
    </p>
  </fieldset>
</form>
</body>
</html>

Try it

required: true The value is required.
required: "#aa:checked" If the value of the expression is true, verification is required.
required: function(){} Returns true, indicating that verification is required.

The latter two are commonly used for elements in the form that need to be filled in or left out at the same time.

Common methods and issues to note

1. Use other methods to replace the default SUBMIT

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

Use ajax method

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

You can set the default value of validate. The writing is 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, only verify and not submit the form

If this parameter is true, the form will not be submitted and only checked, which is very convenient during debugging.

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

If there are multiple forms on a page that you want to set as debug, use:

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

3, ignore: ignore certain elements and do not verify

ignore: ".ignore"

4, Change the position where the error message is displayed

errorPlacement:Callback

Indicate the position where the error is placed. The default is: error.appendTo(element.parent()); that is, the error message is placed behind the verified element.

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

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP中文网(php.cn)</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});

$().ready(function() {
	// 提交时验证表单
	var validator = $("#form1").validate({
		errorPlacement: function(error, element) {
			// Append error within linked label
			$( element )
				.closest( "form" )
					.find( "label[for='" + element.attr( "id" ) + "']" )
						.append( error );
		},
		errorElement: "span",
		messages: {
			user: {
				required: " (必需字段)",
				minlength: " (不能少于 3 个字母)"
			},
			password: {
				required: " (必需字段)",
				minlength: " (字母不能少于 5 个且不能大于 12 个)",
				maxlength: " (字母不能少于 5 个且不能大于 12 个)"
			}
		}
	});

	$(".cancel").click(function() {
		validator.resetForm();
	});
});
</script>
<style>
.error{
	color:red;
}
</style>
</head>
<body>
<form method="get" class="cmxform" id="form1" action="">
  <fieldset>
    <legend>登录框</legend>
    <p>
      <label for="user">用户名</label>
      <input id="user" name="user" required minlength="3">
    </p>
    <p>
      <label for="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>
</body>
</html>

Try it

The function of the code is: Under normal circumstances, the error message is displayed in < td class="status"></td>, if it is radio, it will be displayed in <td></td>, if it is checkbox, it will be displayed behind the content.

## errorClassStringSpecifies the css class name of the error prompt, and you can customize the style of the error prompt. "error"errorElementStringWhat label should be used to mark errors? The default is label, which can be changed to em. "label"errorContainerSelectorDisplay or hide the verification information, which can automatically realize when an error message appears. The container properties become displayed and hidden when there are no errors, which is of little use. ##errorLabelContainerwrapper

Generally, these three attributes are used at the same time to realize the function of displaying all error prompts in a container and automatically hiding it when there is no information.

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

5. Change the style of error message display

Set the style of error prompt, you can add icon display, a validation.css has been established in this system, specially used for maintenance and verification The style of the 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 verified by executing the function

success:String,Callback

The action after the element to be verified passes verification. If followed by a string, it will be treated as a css class, or it can be followed by 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 with the style defined in CSS <style>label.valid {}</style>.

success: "valid"

7. Modify the triggering method of verification

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

ParametersTypeDescriptionDefault value
errorContainer: "#messageBox1, #messageBox2"

SelectorPut the error message Put them uniformly in a container.
StringWhat label should be used to wrap the errorELement above.
Trigger methodTypeDescriptionDefault value
onsubmitBooleanValidate on submission. Set to false to use other methods to verify. true
onfocusoutBooleanValidate when focus is lost (excluding checkboxes/radio buttons). true
onkeyupBooleanValidate on keyup. true
onclickBooleanValidates on click of checkboxes and radio buttons. true
focusInvalidBoolean After submitting the form, the form that failed validation (the first one or obtained before submission The focused (unvalidated) form will gain focus. true
focusCleanupBooleanIf true then remove errors when an element that fails validation gets focus hint. Avoid using it with focusInvalid. false
// 重置表单$().ready(function() { var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();        }    
    });
    $("#reset").click(function() {
        validator.resetForm();    });});

8. Asynchronous verification

remote:URL

Use ajax for verification. By default, the current verified value will be submitted to the remote address. 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" and no other output.

9. Add custom verification

addMethod:name, method, message

Custom verification method

// 中文字两个字节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 or Add in jquery.validate.js file. It is recommended to write it in the additional-methods.js file.

Note: Add: isZipCode: "can only include Chinese characters, English letters, numbers and underlines" in the messages_cn.js file. Add a reference to the additional-methods.js file before calling.

10. Verification of radio, checkbox, and select

The required of radio 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 in checkbox means it must be selected.

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

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

<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 indicates that the selected value 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 of selected items (multi-selectable select), maxlength represents the maximum selected number, and rangelength:[2,3] represents the selected number 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

NameReturn typeDescription
validate(options)ValidatorValidate the selected FORM.
valid()Boolean Check whether the verification is passed.
rules()OptionsReturns the validation rules of the element.
rules("add",rules)OptionsAdd verification rules.
rules("remove",rules)OptionsRemove validation rules.
removeAttrs(attributes)OptionsRemove special attributes and return them.
Custom Selector
:blankValidatorFilter with no value.
:filledArray <Element>Filter with value.
:uncheckedArray <Element>Filter for unselected elements.
Utilities
jQuery.format(template,argument,argumentN...)StringReplace {n} in the template with parameters.

Validator

validate method returns a Validator object. The Validator object has many methods that can be used to trigger the validation program or change the content of the form. Here are some commonly used methods.

NameReturn typeDescription
form()BooleanVerify whether the form returns success or failure.
element(element)BooleanVerifies whether a single element succeeds or fails.
resetForm()undefinedRestore the previously verified FORM to its original state before verification.
showErrors(errors)undefinedShow specific error messages.
Validator function
setDefaults(defaults)undefinedChange the default settings.
addMethod(name,method,message)undefinedAdd a new verification method. Must include a unique name, a JAVASCRIPT method and a default message.
addClassRules(name,rules)undefinedAdd a combined verification type, which is more useful when using multiple verification methods in a class.
addClassRules(rules)undefinedAdd a combined verification type, which is more useful when using multiple verification methods in a class. This is to add multiple verification methods at the same time.

Built-in verification method

NameReturn typeDescription
required ()BooleanRequired validation element.
required(dependency-expression)BooleanRequired elements depend on the result of expression.
required(dependency-callback)BooleanRequired elements depend on the result of the callback function.
remote(url)BooleanRequest remote verification. url is usually a remote call method.
minlength(length)BooleanSet the minimum length.
maxlength(length)BooleanSet the maximum length.
rangelength(range)BooleanSet a length range [min,max].
min(value)BooleanSet the minimum value.
max(value)BooleanSet the maximum value.
email()BooleanVerify the email format.
range(range)BooleanSet the range of values.
url()BooleanVerify URL format.
date()BooleanVerify the date format (similar to the format of 30/30/2008, the date accuracy is not verified, only the format is verified) .
dateISO()BooleanVerify the ISO type date format.
dateDE()BooleanVerifies the German date format (29.04.1994 or 1.1.2006).
number()BooleanValidate decimal numbers (including decimals).
digits()BooleanValidate integers.
creditcard()BooleanVerify credit card number.
accept(extension)BooleanVerify strings with the same suffix name.
equalTo(other)BooleanVerify whether the contents of the two input boxes are the same.
phoneUS()BooleanVerify the US phone number.

validate() options

##DescriptionCodedebug: Enter debug mode ( The form is not submitted).
$(".selector").validate({
	debug:true})
Set debugging as default.
$.validator.setDefaults({
	debug:true})
submitHandler: The function that is run after passing verification 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 the form of key:value, key is the element to be verified, and value can be a string or object.
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true}}})
messages: Custom prompt message, in the form of key:value, key is the element to be verified, and value can be a string or a function.
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true}},
	messages:{
		name:"Name不能为空",
		email:{       
			required:"E-mail不能为空",
			email:"E-mail地址不正确"}}})
groups: Verify a group of elements, use an error prompt, and use errorPlacement to control where the error information 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 verify when submitting.
$(".selector").validate({  
	onsubmit:false})
onfocusout: Type Boolean, default true, specifies whether to verify when getting focus.
$(".selector").validate({   
	onfocusout:false})
onkeyup: Type Boolean, default true, specifies whether to verify when the keyboard is struck.
$(".selector").validate({
   onkeyup:false})
onclick: Type Boolean, default true, specifies whether to verify when the mouse clicks (generally verify checkbox, radiobox).
$(".selector").validate({
   onclick:false})
focusInvalid: Type Boolean, default true. After a form is submitted, the form that fails validation (either the first failed validation form or one that received focus before submission) gets focus.
$(".selector").validate({
   focusInvalid:false})
focusCleanup: Type Boolean, default false. Remove error message when unvalidated element gets focus (avoid using with 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 label to use to mark errors.
$(".selector").validate
   errorElement:"em"})
wrapper: Type String, specify what label to use and wrap the above errorELement.
$(".selector").validate({
   wrapper:"li"})
errorLabelContainer: Type Selector, which puts error information in a container.
$("#myform").validate({   
	errorLabelContainer:"#messageBox",
	wrapper:"li",
	submitHandler:function() { 
		alert("Submitted!") 
	}})
showErrors: Followed by a function to display the total number of elements that failed validation.
$(".selector").validate({  
	showErrors:function(errorMap,errorList) {
        $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");this.defaultShowErrors();}})
errorPlacement: With a function, you can customize where errors are placed.
$("#myform").validate({  
	errorPlacement:function(error,element) {  
		error.appendTo(element.parent("td").next("td"));   },
   debug:true})
#success: The action after the element to be verified passes verification. If followed by a string, it will be treated as a css class, or it can be followed by a function.
$("#myform").validate({        
	success:"valid",
        submitHandler:function() { 
			alert("Submitted!") 
		}})
Highlight: You can add effects, flicker, etc. to elements that have not passed verification.

addMethod(name, method, message) method

Parameter name is the name of the added method.

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

We can use addMethod to add validation methods other than the built-in Validation method. For example, there is a field in which you can only enter one letter, and the range is a-f. The writing method is 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 id="username", write in rules:

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

The first parameter of addMethod is the name of the added verification method, which is af in this case.
The third parameter of addMethod is a customized error prompt. The prompt here is: "Must be a letter, and a-f".
The second parameter of addMethod is a function. This is more important and determines the writing method when using this verification method.

If there is only one parameter, write it directly, such as af: "a", then a is the only parameter. If there are multiple parameters, write them in [] and separate them with commas.

meta String method

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




##Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网</title> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().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: "请选择两个主题" } }); }); </script> <style> .error{ color:red; } </style> </head> <body> <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" style="display:none">至少选择两个</label> </fieldset> <p> <input class="submit" type="submit" value="提交"> </p> </fieldset> </form> </body> </html>
submitReset Code
ChapterCourseware
    None