亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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: "請輸入有效的網(wǎng)址",
	date: "請輸入有效的日期",
	dateISO: "請輸入有效的日期 (YYYY-MM-DD)",
	number: "請輸入有效的數(shù)字",
	digits: "只能輸入數(shù)字",
	creditcard: "請輸入有效的信用卡號碼",
	equalTo: "你的輸入不相同",
	extension: "請輸入有效的后綴",
	maxlength: $.validator.format("最多可以輸入 {0} 個字符"),
	minlength: $.validator.format("最少要輸入 {0} 個字符"),
	rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字符串"),
	range: $.validator.format("請輸入范圍在 {0} 到 {1} 之間的數(shù)值"),
	max: $.validator.format("請輸入不大于 {0} 的數(shù)值"),
	min: $.validator.format("請輸入不小于 {0} 的數(shù)值")});}));

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中文網(wǎng)(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中文網(wǎng)(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中文網(wǎng)(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",               //數(shù)據(jù)發(fā)送方式
    dataType: "json",           //接受數(shù)據(jù)格式   
    data: {                     //要傳遞的數(shù)據(jù)
        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

// 中文字兩個字節(jié)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}個字節(jié)之間(一個中文字算2個字節(jié))"));// 郵政編碼驗證   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>




## Continuing Learning

||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文網(wǎng)</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