国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

jQuery中文參考手冊(cè) / jQuery Validate

jQuery Validate

jQuery Validate

jQuery Validate 插件為表單提供了強(qiáng)大的驗(yàn)證功能,讓客戶端表單驗(yàn)證變得更簡(jiǎn)單,同時(shí)提供了大量的定制選項(xiàng),滿足應(yīng)用程序各種需求。該插件捆綁了一套有用的驗(yàn)證方法,包括 URL 和電子郵件驗(yàn)證,同時(shí)提供了一個(gè)用來(lái)編寫用戶自定義方法的 API。所有的捆綁方法默認(rèn)使用英語(yǔ)作為錯(cuò)誤信息,且已翻譯成其他 37 種語(yǔ)言。

該插件是由 J?rn Zaefferer 編寫和維護(hù)的,他是 jQuery 團(tuán)隊(duì)的一名成員,是 jQuery UI 團(tuán)隊(duì)的主要開發(fā)人員,是 QUnit 的維護(hù)人員。該插件在 2006 年 jQuery 早期的時(shí)候就已經(jīng)開始出現(xiàn),并一直更新至今。目前版本是  1.14.0。

訪問(wèn) jQuery Validate 官網(wǎng),下載最新版的 jQuery Validate 插件。

默認(rèn)校驗(yàn)規(guī)則

序號(hào)規(guī)則描述
1required:true必須輸入的字段。
2remote:"check.php"使用 ajax 方法調(diào)用 check.php 驗(yàn)證輸入值。
3email:true必須輸入正確格式的電子郵件。
4url:true必須輸入正確格式的網(wǎng)址。
5date:true必須輸入正確格式的日期。日期校驗(yàn) ie6 出錯(cuò),慎用。
6dateISO:true必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗(yàn)證格式,不驗(yàn)證有效性。
7number:true必須輸入合法的數(shù)字(負(fù)數(shù),小數(shù))。
8digits:true必須輸入整數(shù)。
9creditcard:必須輸入合法的信用卡號(hào)。
10equalTo:"#field"輸入值必須和 #field 相同。
11accept:輸入擁有合法后綴名的字符串(上傳文件的后綴)。
12maxlength:5輸入長(zhǎng)度最多是 5 的字符串(漢字算一個(gè)字符)。
13minlength:10輸入長(zhǎng)度最小是 10 的字符串(漢字算一個(gè)字符)。
14rangelength:[5,10]輸入長(zhǎng)度必須介于 5 和 10 之間的字符串(漢字算一個(gè)字符)。
15range:[5,10]輸入值必須介于 5 和 10 之間。
16max:5輸入值不能大于 5。
17min:10輸入值不能小于 10。

默認(rèn)提示

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提供了中文信息提示包,位于下載包的 dist/localization/messages_zh.js,內(nèi)容如下:

(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), 漢語(yǔ), 漢語(yǔ))
 */$.extend($.validator.messages, {
	required: "這是必填字段",
	remote: "請(qǐng)修正此字段",
	email: "請(qǐng)輸入有效的電子郵件地址",
	url: "請(qǐng)輸入有效的網(wǎng)址",
	date: "請(qǐng)輸入有效的日期",
	dateISO: "請(qǐng)輸入有效的日期 (YYYY-MM-DD)",
	number: "請(qǐng)輸入有效的數(shù)字",
	digits: "只能輸入數(shù)字",
	creditcard: "請(qǐng)輸入有效的信用卡號(hào)碼",
	equalTo: "你的輸入不相同",
	extension: "請(qǐng)輸入有效的后綴",
	maxlength: $.validator.format("最多可以輸入 {0} 個(gè)字符"),
	minlength: $.validator.format("最少要輸入 {0} 個(gè)字符"),
	rangelength: $.validator.format("請(qǐng)輸入長(zhǎng)度在 {0} 到 {1} 之間的字符串"),
	range: $.validator.format("請(qǐng)輸入范圍在 {0} 到 {1} 之間的數(shù)值"),
	max: $.validator.format("請(qǐng)輸入不大于 {0} 的數(shù)值"),
	min: $.validator.format("請(qǐng)輸入不小于 {0} 的數(shù)值")});}));

你可以將該本地化信息文件 dist/localization/messages_zh.js 引入到頁(yè)面:

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

使用方式

1、將校驗(yàn)規(guī)則寫到控件中

實(shí)例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<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 (必需, 最小兩個(gè)字母)</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>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例

2、將校驗(yàn)規(guī)則寫到 js 代碼中

$().ready(function() {// 在鍵盤按下并釋放及提交后驗(yàn)證提交表單
  $("#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: "請(qǐng)輸入您的名字",
      lastname: "請(qǐng)輸入您的姓氏",
      username: {
        required: "請(qǐng)輸入用戶名",
        minlength: "用戶名必需由兩個(gè)字母組成"      },
      password: {
        required: "請(qǐng)輸入密碼",
        minlength: "密碼長(zhǎng)度不能小于 5 個(gè)字母"      },
      confirm_password: {
        required: "請(qǐng)輸入密碼",
        minlength: "密碼長(zhǎng)度不能小于 5 個(gè)字母",
        equalTo: "兩次密碼輸入不一致"      },
      email: "請(qǐng)輸入一個(gè)正確的郵箱",
      agree: "請(qǐng)接受我們的聲明",
      topic: "請(qǐng)選擇兩個(gè)主題"    }});

messages 處,如果某個(gè)控件沒有 message,將調(diào)用默認(rèn)的信息

實(shí)例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<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() {
// 在鍵盤按下并釋放及提交后驗(yàn)證提交表單
  $("#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: "請(qǐng)輸入您的名字",
	      lastname: "請(qǐng)輸入您的姓氏",
	      username: {
	        required: "請(qǐng)輸入用戶名",
	        minlength: "用戶名必需由兩個(gè)字母組成"
	      },
	      password: {
	        required: "請(qǐng)輸入密碼",
	        minlength: "密碼長(zhǎng)度不能小于 5 個(gè)字母"
	      },
	      confirm_password: {
	        required: "請(qǐng)輸入密碼",
	        minlength: "密碼長(zhǎng)度不能小于 5 個(gè)字母",
	        equalTo: "兩次密碼輸入不一致"
	      },
	      email: "請(qǐng)輸入一個(gè)正確的郵箱",
	      agree: "請(qǐng)接受我們的聲明",
	      topic: "請(qǐng)選擇兩個(gè)主題"
	    }
	});
});
</script>
<style>
.error{
	color:red;
}
</style>
</head>
<body>
<form class="cmxform" id="signupForm" method="get" action="">
  <fieldset>
    <legend>驗(yàn)證完整的表單</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">驗(yàn)證密碼</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">請(qǐng)同意我們的聲明</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>主題 (至少選擇兩個(gè)) - 注意:如果沒有勾選“我樂意接收新信息”以下選項(xiàng)會(huì)隱藏,但我們這里作為演示讓它可見</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">至少選擇兩個(gè)</label>
    </fieldset>
    <p>
      <input class="submit" type="submit" value="提交">
    </p>
  </fieldset>
</form>
</body>
</html>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例

required: true 值是必須的。
required: "#aa:checked" 表達(dá)式的值為真,則需要驗(yàn)證。
required: function(){} 返回為真,表示需要驗(yàn)證。

后邊兩種常用于,表單中需要同時(shí)填或不填的元素。

常用方法及注意問(wèn)題

1、用其他方式替代默認(rèn)的 SUBMIT

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

使用 ajax 方式

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

可以設(shè)置 validate 的默認(rèn)值,寫法如下:

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

如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。

2、debug,只驗(yàn)證不提交表單

如果這個(gè)參數(shù)為true,那么表單不會(huì)提交,只進(jìn)行檢查,調(diào)試時(shí)十分方便。

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

如果一個(gè)頁(yè)面中有多個(gè)表單都想設(shè)置成為 debug,則使用:

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

3、ignore:忽略某些元素不驗(yàn)證

ignore: ".ignore"

4、更改錯(cuò)誤信息顯示的位置

errorPlacement:Callback

指明錯(cuò)誤放置的位置,默認(rèn)情況是:error.appendTo(element.parent());即把錯(cuò)誤信息放在驗(yàn)證的元素后面。

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

實(shí)例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<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() {
	// 提交時(shí)驗(yàn)證表單
	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 個(gè)字母)"
			},
			password: {
				required: " (必需字段)",
				minlength: " (字母不能少于 5 個(gè)且不能大于 12 個(gè))",
				maxlength: " (字母不能少于 5 個(gè)且不能大于 12 個(gè))"
			}
		}
	});

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

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例

代碼的作用是:一般情況下把錯(cuò)誤信息顯示在 <td class="status"></td> 中,如果是 radio 則顯示在 <td></td> 中,如果是 checkbox 則顯示在內(nèi)容的后面。

參數(shù)類型描述默認(rèn)值
errorClassString指定錯(cuò)誤提示的 css 類名,可以自定義錯(cuò)誤提示的樣式。"error"
errorElementString用什么標(biāo)簽標(biāo)記錯(cuò)誤,默認(rèn)是 label,可以改成 em。"label"
errorContainerSelector顯示或者隱藏驗(yàn)證信息,可以自動(dòng)實(shí)現(xiàn)有錯(cuò)誤信息出現(xiàn)時(shí)把容器屬性變?yōu)轱@示,無(wú)錯(cuò)誤時(shí)隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2"

errorLabelContainerSelector把錯(cuò)誤信息統(tǒng)一放在一個(gè)容器里面。
wrapperString用什么標(biāo)簽再把上邊的 errorELement 包起來(lái)。

一般這三個(gè)屬性同時(shí)使用,實(shí)現(xiàn)在一個(gè)容器內(nèi)顯示所有錯(cuò)誤提示的功能,并且沒有信息時(shí)自動(dòng)隱藏。

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

5、更改錯(cuò)誤信息顯示的樣式

設(shè)置錯(cuò)誤提示的樣式,可以增加圖標(biāo)顯示,在該系統(tǒng)中已經(jīng)建立了一個(gè) validation.css,專門用于維護(hù)校驗(yàn)文件的樣式。

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、每個(gè)字段驗(yàn)證通過(guò)執(zhí)行函數(shù)

success:String,Callback

要驗(yàn)證的元素通過(guò)驗(yàn)證后的動(dòng)作,如果跟一個(gè)字符串,會(huì)當(dāng)作一個(gè) css 類,也可跟一個(gè)函數(shù)。

success: function(label) {    // set &nbsp; as text for IE
    label.html("&nbsp;").addClass("checked");    //label.addClass("valid").text("Ok!")}

添加 "valid" 到驗(yàn)證元素,在 CSS 中定義的樣式 <style>label.valid {}</style>。

success: "valid"

7、驗(yàn)證的觸發(fā)方式修改

下面的雖然是 boolean 型的,但建議除非要改為 false,否則別亂添加。

觸發(fā)方式類型描述默認(rèn)值
onsubmitBoolean提交時(shí)驗(yàn)證。設(shè)置為 false 就用其他方法去驗(yàn)證。true
onfocusoutBoolean失去焦點(diǎn)時(shí)驗(yàn)證(不包括復(fù)選框/單選按鈕)。true
onkeyupBoolean在 keyup 時(shí)驗(yàn)證。true
onclickBoolean在點(diǎn)擊復(fù)選框和單選按鈕時(shí)驗(yàn)證。true
focusInvalidBoolean提交表單后,未通過(guò)驗(yàn)證的表單(第一個(gè)或提交之前獲得焦點(diǎn)的未通過(guò)驗(yàn)證的表單)會(huì)獲得焦點(diǎn)。true
focusCleanupBoolean如果是 true 那么當(dāng)未通過(guò)驗(yàn)證的元素獲得焦點(diǎn)時(shí),移除錯(cuò)誤提示。避免和 focusInvalid 一起用。false
// 重置表單$().ready(function() { var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();        }    
    });
    $("#reset").click(function() {
        validator.resetForm();    });});

8、異步驗(yàn)證

remote:URL

使用 ajax 方式進(jìn)行驗(yàn)證,默認(rèn)會(huì)提交當(dāng)前驗(yàn)證的值到遠(yuǎn)程地址,如果需要提交其他的值,可以使用 data 選項(xiàng)。

remote: "check-email.php"
remote: {
    url: "check-email.php",     //后臺(tái)處理程序
    type: "post",               //數(shù)據(jù)發(fā)送方式
    dataType: "json",           //接受數(shù)據(jù)格式   
    data: {                     //要傳遞的數(shù)據(jù)
        username: function() {            return $("#username").val();        }    }}

遠(yuǎn)程地址只能輸出 "true" 或 "false",不能有其他輸出。

9、添加自定義校驗(yàn)

addMethod:name, method, message

自定義驗(yàn)證方法

// 中文字兩個(gè)字節(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("請(qǐng)確保輸入的值在{0}-{1}個(gè)字節(jié)之間(一個(gè)中文字算2個(gè)字節(jié))"));// 郵政編碼驗(yàn)證   jQuery.validator.addMethod("isZipCode", function(value, element) {   
    var tel = /^[0-9]{6}$/;    return this.optional(element) || (tel.test(value));}, "請(qǐng)正確填寫您的郵政編碼");

注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建議一般寫在 additional-methods.js 文件中。

注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、數(shù)字和下劃線"。調(diào)用前要添加對(duì) additional-methods.js 文件的引用。

10、radio 和 checkbox、select 的驗(yàn)證

radio 的 required 表示必須選中一個(gè)。

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

checkbox 的 required 表示必須選中。

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

checkbox 的 minlength 表示必須選中的最小個(gè)數(shù),maxlength 表示最大的選中個(gè)數(shù),rangelength:[2,3] 表示選中個(gè)數(shù)區(qū)間。

<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 的 required 表示選中的 value 不能為空。

<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 的 minlength 表示選中的最小個(gè)數(shù)(可多選的 select),maxlength 表示最大的選中個(gè)數(shù),rangelength:[2,3] 表示選中個(gè)數(shù)區(qū)間。

<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 中文 API

名稱返回類型描述
validate(options)Validator驗(yàn)證所選的 FORM。
valid()Boolean檢查是否驗(yàn)證通過(guò)。
rules()Options返回元素的驗(yàn)證規(guī)則。
rules("add",rules)Options增加驗(yàn)證規(guī)則。
rules("remove",rules)Options刪除驗(yàn)證規(guī)則。
removeAttrs(attributes)Options刪除特殊屬性并且返回它們。
自定義選擇器
:blankValidator沒有值的篩選器。
:filledArray <Element>有值的篩選器。
:uncheckedArray <Element>沒選擇的元素的篩選器。
實(shí)用工具
jQuery.format(template,argument,argumentN...)String用參數(shù)代替模板中的 {n}。

Validator

validate 方法返回一個(gè) Validator 對(duì)象。Validator 對(duì)象有很多方法可以用來(lái)引發(fā)校驗(yàn)程序或者改變 form 的內(nèi)容,下面列出幾個(gè)常用的方法。

名稱返回類型描述
form()Boolean驗(yàn)證 form 返回成功還是失敗。
element(element)Boolean驗(yàn)證單個(gè)元素是成功還是失敗。
resetForm()undefined把前面驗(yàn)證的 FORM 恢復(fù)到驗(yàn)證前原來(lái)的狀態(tài)。
showErrors(errors)undefined顯示特定的錯(cuò)誤信息。
Validator 函數(shù)
setDefaults(defaults)undefined改變默認(rèn)的設(shè)置。
addMethod(name,method,message)undefined添加一個(gè)新的驗(yàn)證方法。必須包括一個(gè)獨(dú)一無(wú)二的名字,一個(gè) JAVASCRIPT 的方法和一個(gè)默認(rèn)的信息。
addClassRules(name,rules)undefined增加組合驗(yàn)證類型,在一個(gè)類里面用多種驗(yàn)證方法時(shí)比較有用。
addClassRules(rules)undefined增加組合驗(yàn)證類型,在一個(gè)類里面用多種驗(yàn)證方法時(shí)比較有用。這個(gè)是同時(shí)加多個(gè)驗(yàn)證方法。

內(nèi)置驗(yàn)證方式

名稱返回類型描述
required()Boolean必填驗(yàn)證元素。
required(dependency-expression)Boolean必填元素依賴于表達(dá)式的結(jié)果。
required(dependency-callback)Boolean必填元素依賴于回調(diào)函數(shù)的結(jié)果。
remote(url)Boolean請(qǐng)求遠(yuǎn)程校驗(yàn)。url 通常是一個(gè)遠(yuǎn)程調(diào)用方法。
minlength(length)Boolean設(shè)置最小長(zhǎng)度。
maxlength(length)Boolean設(shè)置最大長(zhǎng)度。
rangelength(range)Boolean設(shè)置一個(gè)長(zhǎng)度范圍 [min,max]。
min(value)Boolean設(shè)置最小值。
max(value)Boolean設(shè)置最大值。
email()Boolean驗(yàn)證電子郵箱格式。
range(range)Boolean設(shè)置值的范圍。
url()Boolean驗(yàn)證 URL 格式。
date()Boolean驗(yàn)證日期格式(類似 30/30/2008 的格式,不驗(yàn)證日期準(zhǔn)確性只驗(yàn)證格式)。
dateISO()Boolean驗(yàn)證 ISO 類型的日期格式。
dateDE()Boolean驗(yàn)證德式的日期格式(29.04.1994 或 1.1.2006)。
number()Boolean驗(yàn)證十進(jìn)制數(shù)字(包括小數(shù)的)。
digits()Boolean驗(yàn)證整數(shù)。
creditcard()Boolean驗(yàn)證信用卡號(hào)。
accept(extension)Boolean驗(yàn)證相同后綴名的字符串。
equalTo(other)Boolean驗(yàn)證兩個(gè)輸入框的內(nèi)容是否相同。
phoneUS()Boolean驗(yàn)證美式的電話號(hào)碼。

validate ()的可選項(xiàng)

描述代碼
debug:進(jìn)行調(diào)試模式(表單不提交)。
$(".selector").validate({
	debug:true})
把調(diào)試設(shè)置為默認(rèn)。
$.validator.setDefaults({
	debug:true})
submitHandler:通過(guò)驗(yàn)證后運(yùn)行的函數(shù),里面要加上表單提交的函數(shù),否則表單不會(huì)提交。
$(".selector").validate({
	submitHandler:function(form) {
		$(form).ajaxSubmit();}})
ignore:對(duì)某些元素不進(jìn)行驗(yàn)證。
$("#myform").validate({
	ignore:".ignore"})
rules:自定義規(guī)則,key:value 的形式,key 是要驗(yàn)證的元素,value 可以是字符串或?qū)ο蟆?/td>
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true}}})
messages:自定義的提示信息,key:value 的形式,key 是要驗(yàn)證的元素,value 可以是字符串或函數(shù)。
$(".selector").validate({
	rules:{
		name:"required",
		email:{
			required:true,
			email:true}},
	messages:{
		name:"Name不能為空",
		email:{       
			required:"E-mail不能為空",
			email:"E-mail地址不正確"}}})
groups:對(duì)一組元素的驗(yàn)證,用一個(gè)錯(cuò)誤提示,用 errorPlacement 控制把出錯(cuò)信息放在哪里。
$("#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,默認(rèn) true,指定是否提交時(shí)驗(yàn)證。
$(".selector").validate({  
	onsubmit:false})
onfocusout:類型 Boolean,默認(rèn) true,指定是否在獲取焦點(diǎn)時(shí)驗(yàn)證。
$(".selector").validate({   
	onfocusout:false})
onkeyup:類型 Boolean,默認(rèn) true,指定是否在敲擊鍵盤時(shí)驗(yàn)證。
$(".selector").validate({
   onkeyup:false})
onclick:類型 Boolean,默認(rèn) true,指定是否在鼠標(biāo)點(diǎn)擊時(shí)驗(yàn)證(一般驗(yàn)證 checkbox、radiobox)。
$(".selector").validate({
   onclick:false})
focusInvalid:類型 Boolean,默認(rèn) true。提交表單后,未通過(guò)驗(yàn)證的表單(第一個(gè)或提交之前獲得焦點(diǎn)的未通過(guò)驗(yàn)證的表單)會(huì)獲得焦點(diǎn)。
$(".selector").validate({
   focusInvalid:false})
focusCleanup:類型 Boolean,默認(rèn) false。當(dāng)未通過(guò)驗(yàn)證的元素獲得焦點(diǎn)時(shí),移除錯(cuò)誤提示(避免和 focusInvalid 一起使用)。
$(".selector").validate({
   focusCleanup:true})
errorClass:類型 String,默認(rèn) "error"。指定錯(cuò)誤提示的 css 類名,可以自定義錯(cuò)誤提示的樣式。
$(".selector").validate({ 
	errorClass:"invalid"})
errorElement:類型 String,默認(rèn) "label"。指定使用什么標(biāo)簽標(biāo)記錯(cuò)誤。
$(".selector").validate
   errorElement:"em"})
wrapper:類型 String,指定使用什么標(biāo)簽再把上邊的 errorELement 包起來(lái)。
$(".selector").validate({
   wrapper:"li"})
errorLabelContainer:類型 Selector,把錯(cuò)誤信息統(tǒng)一放在一個(gè)容器里面。
$("#myform").validate({   
	errorLabelContainer:"#messageBox",
	wrapper:"li",
	submitHandler:function() { 
		alert("Submitted!") 
	}})
showErrors:跟一個(gè)函數(shù),可以顯示總共有多少個(gè)未通過(guò)驗(yàn)證的元素。
$(".selector").validate({  
	showErrors:function(errorMap,errorList) {
        $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");this.defaultShowErrors();}})
errorPlacement:跟一個(gè)函數(shù),可以自定義錯(cuò)誤放到哪里。
$("#myform").validate({  
	errorPlacement:function(error,element) {  
		error.appendTo(element.parent("td").next("td"));   },
   debug:true})
success:要驗(yàn)證的元素通過(guò)驗(yàn)證后的動(dòng)作,如果跟一個(gè)字符串,會(huì)當(dāng)作一個(gè) css 類,也可跟一個(gè)函數(shù)。
$("#myform").validate({        
	success:"valid",
        submitHandler:function() { 
			alert("Submitted!") 
		}})
highlight:可以給未通過(guò)驗(yàn)證的元素加效果、閃爍等。

addMethod(name,method,message)方法

參數(shù) name 是添加的方法的名字。

參數(shù) method 是一個(gè)函數(shù),接收三個(gè)參數(shù) (value,element,param) 。
value 是元素的值,element 是元素本身,param 是參數(shù)。

我們可以用 addMethod 來(lái)添加除內(nèi)置的 Validation 方法之外的驗(yàn)證方法。比如有一個(gè)字段,只能輸一個(gè)字母,范圍是 a-f,寫法如下:

$.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;}},"必須是一個(gè)字母,且a-f");

如果有個(gè)表單字段的 id="username",則在 rules 中寫:

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

addMethod 的第一個(gè)參數(shù),是添加的驗(yàn)證方法的名字,這時(shí)是 af。
addMethod 的第三個(gè)參數(shù),是自定義的錯(cuò)誤提示,這里的提示為:"必須是一個(gè)字母,且a-f"。
addMethod 的第二個(gè)參數(shù),是一個(gè)函數(shù),這個(gè)比較重要,決定了用這個(gè)驗(yàn)證方法時(shí)的寫法。

如果只有一個(gè)參數(shù),直接寫,比如 af:"a",那么 a 就是這個(gè)唯一的參數(shù),如果多個(gè)參數(shù),則寫在 [] 里,用逗號(hào)分開。

meta String 方式

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

實(shí)例演示

虛構(gòu)的實(shí)例

  • 錯(cuò)誤消息容器
  • 自定義消息作為元素?cái)?shù)據(jù)
  • radio(單選按鈕)、checkbox(復(fù)選按鈕)和 select(下拉框)
  • 與表單(Form)插件的交互(AJAX 提交)
  • 自定義方法和消息顯示
  • 動(dòng)態(tài)表單
  • 使用 jQuery UI Themeroller 定義表單樣式
  • TinyMCE - 一個(gè)輕量級(jí)的基于瀏覽器的所見即所得編輯器
  • 文件輸入框
  • jQuery Mobile 表單驗(yàn)證

現(xiàn)實(shí)世界的實(shí)例

  • Milk 注冊(cè)表單
  • Marketo 注冊(cè)表單
  • 房屋買賣折疊面板表單
  • 遠(yuǎn)程 CAPTCHA(驗(yàn)證碼)驗(yàn)證