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

jQuery 驗(yàn)證

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)編寫(xiě)使用者自訂方法的 API。所有的捆綁方法預(yù)設(shè)使用英語(yǔ)作為錯(cuò)誤訊息,且已翻譯成其他 37 種語(yǔ)言。

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

造訪 jQuery Validate 官網(wǎng),下載最新版的 jQuery Validate 外掛。

匯入js 函式庫(kù)

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

預(yù)設(shè)校驗(yàn)規(guī)則

#序號(hào)#規(guī)則描述
1required:true#必須輸入的欄位。
2remote:"check.php"使用 ajax 方法呼叫 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。

預(yù)設(shè)提示

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 引進(jìn)到頁(yè)面:

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

使用方式

1、將校驗(yàn)規(guī)則寫(xiě)到控制項(xiàng)中

<!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 (必需, 最小兩個(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>

#試試看?

#2、將校驗(yàn)規(guī)則寫(xiě)到j(luò)s 程式碼中

$().ready(function() {// 在鍵盤(pán)按下并釋放及提交后驗(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è)控制項(xiàng)沒(méi)有message,會(huì)呼叫預(yù)設(shè)的資訊

<!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() {
// 在鍵盤(pán)按下并釋放及提交后驗(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">我樂(lè)意接收新信息</label>
      <input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
    </p>
    <fieldset id="newsletter_topics">
      <legend>主題 (至少選擇兩個(gè)) - 注意:如果沒(méi)有勾選“我樂(lè)意接收新信息”以下選項(xiàng)會(huì)隱藏,但我們這里作為演示讓它可見(jiàn)</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>

試試看?

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

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

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

1、用其他方式取代預(yù)設(shè)的SUBMIT

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

使用ajax 方式

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

可以設(shè)定validate 的預(yù)設(shè)值,寫(xiě)法如下:

$.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ò)誤放置的位置,預(yù)設(shè)是:error.appendTo(element.parent());即把錯(cuò)誤訊息放在驗(yàn)證的元素後面。

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

實(shí)例

<!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() {
	// 提交時(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>

試試看?

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

參數(shù)類(lèi)型描述預(yù)設(shè)值
errorClassString指定錯(cuò)誤提示的css 類(lèi)別名,可以自訂錯(cuò)誤提示的樣式。 "error"
errorElementString用什麼標(biāo)籤標(biāo)記錯(cuò)誤,預(yù)設(shè)是 label,可以改成 em。 "label"
errorContainer#Selector顯示或隱藏驗(yàn)證訊息,可以自動(dòng)實(shí)作有錯(cuò)誤訊息出現(xiàn)時(shí)把容器屬性變成顯示,無(wú)錯(cuò)誤時(shí)隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2"

errorLabelContainer#Selector把錯(cuò)誤訊息統(tǒng)一放在一個(gè)容器裡面。
wrapperString用什麼標(biāo)籤再把上邊的 errorELement 包起來(lái)。

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

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

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

設(shè)定錯(cuò)誤提示的樣式,可以增加圖示顯示,在該系統(tǒng)中已經(jīng)建立了一個(gè)validation.css,專(zhuān)門(mén)用於維護(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 類(lèi),也可跟一個(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,否則別亂添加。

onsubmitBoolean提交時(shí)驗(yàn)證。設(shè)定為 false 就用其他方法去驗(yàn)證。 trueonfocusoutBoolean失去焦點(diǎn)時(shí)驗(yàn)證(不包含複選框/單選按鈕)。 trueonkeyupBoolean在 keyup 時(shí)驗(yàn)證。 trueonclickBoolean在點(diǎn)擊複選框和單選按鈕時(shí)驗(yàn)證。 truefocusInvalidBoolean提交表單後,未通過(guò)驗(yàn)證的表單(第一個(gè)或提交之前獲得焦點(diǎn)的未通過(guò)驗(yàn)證的表單)會(huì)獲得焦點(diǎn)。 truefocusCleanupBoolean如果是true 那麼當(dāng)未通過(guò)驗(yàn)證的元素獲得焦點(diǎn)時(shí),移除錯(cuò)誤提示。避免和 focusInvalid 一起用。 false
觸發(fā)方式#類(lèi)型描述預(yù)設(shè)值
#########
// 重置表單$().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)證,預(yù)設(shè)會(huì)提交目前驗(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)正確填寫(xiě)您的郵政編碼");

注意:要在additional-methods.js 檔案中新增或者在jquery.validate.js 檔案中新增。建議一般寫(xiě)在 additional-methods.js 檔案中。

注意:在 messages_cn.js 檔案中新增:isZipCode: "只能包含中文字、英文字母、數(shù)字和底線"。呼叫前要加入 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)valid()rules()rules("add",rules)增加驗(yàn)證規(guī)則。 刪除驗(yàn)證規(guī)則。 刪除特殊屬性並且傳回它們。 :blank沒(méi)有值的篩選器。 有值的篩選器。
#名稱(chēng)#描述
Validator驗(yàn)證所選的FORM。
Boolean檢查是否驗(yàn)證通過(guò)。
Options傳回元素的驗(yàn)證規(guī)則。
Options
rules("remove",rules)Options
removeAttrs(attributes)Options
自訂選擇器
Validator
:filledArray <Element>
######:unchecked######Array <Element>######沒(méi)選擇的元素的篩選器。 ############實(shí)用工具############jQuery.format(template,argument,argumentN...)##################################################### ##用參數(shù)取代模板中的{n}。 ############

Validator

validate 方法傳回一個(gè) Validator 物件。 Validator 物件有很多方法可以用來(lái)引發(fā)校驗(yàn)程式或改變 form 的內(nèi)容,以下列出幾個(gè)常用的方法。

##form()Boolean驗(yàn)證form 回傳成功還是失敗。 element(element)Boolean#驗(yàn)證單一元素是成功還是失敗。 resetForm()undefined#把前面驗(yàn)證的 FORM 恢復(fù)到驗(yàn)證前原來(lái)的狀態(tài)。 showErrors(errors)undefined顯示特定的錯(cuò)誤訊息。 Validator 函數(shù)setDefaults(defaults)undefinedaddMethod(name,method,message)addClassRules(name,rules)addClassRules(rules)

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

名稱(chēng)傳回類(lèi)型描述
##改變預(yù)設(shè)的設(shè)定。
undefined新增一個(gè)新的驗(yàn)證方法。必須包含一個(gè)獨(dú)一無(wú)二的名字,一個(gè) JAVASCRIPT 的方法和一個(gè)預(yù)設(shè)的訊息。
undefined增加組合驗(yàn)證類(lèi)型,在一個(gè)類(lèi)別裡面用多種驗(yàn)證方法時(shí)比較有用。
undefined增加組合驗(yàn)證類(lèi)型,在一個(gè)類(lèi)別裡面用多種驗(yàn)證方法時(shí)比較有用。這個(gè)是同時(shí)加多個(gè)驗(yàn)證方法。
名稱(chēng)傳回類(lèi)型說(shuō)明
required ()Boolean必填驗(yàn)證元素。
required(dependency-expression)Boolean必填元素依賴(lài)表達(dá)式的結(jié)果。
required(dependency-callback)Boolean必填元素依賴(lài)回呼函數(shù)的結(jié)果。
remote(url)Boolean#請(qǐng)求遠(yuǎn)端校驗(yàn)。 url 通常是遠(yuǎn)端呼叫方法。
minlength(length)Boolean設(shè)定最小長(zhǎng)度。
maxlength(length)Boolean設(shè)定最大長(zhǎng)度。
rangelength(range)Boolean設(shè)定一個(gè)長(zhǎng)度範(fàn)圍 [min,max]。
min(value)Boolean#設(shè)定最小值。
max(value)Boolean#設(shè)定最大值。
email()Boolean驗(yàn)證電子郵件信箱格式。
range(range)Boolean設(shè)定值的範(fàn)圍。
url()Boolean驗(yàn)證 URL 格式。
date()Boolean驗(yàn)證日期格式(類(lèi)似30/30/2008 的格式,不驗(yàn)證日期準(zhǔn)確度只驗(yàn)證格式) 。
dateISO()Boolean#驗(yàn)證 ISO 類(lèi)型的日期格式。
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)行偵錯(cuò)模式(表單不提交)。
$(".selector").validate({
	debug:true})
把偵錯(cuò)設(shè)定為預(yù)設(shè)。
$.validator.setDefaults({
	debug:true})
submitHandler:經(jīng)過(guò)驗(yàn)證後執(zhí)行的函數(shù),裡面要加上表單提交的函數(shù),否則表單不會(huì)提交。
$(".selector").validate({
	submitHandler:function(form) {
		$(form).ajaxSubmit();}})
ignore:不驗(yàn)證某些元素。
$("#myform").validate({
	ignore:".ignore"})
rules:自訂規(guī)則,key:value 的形式,key 是要驗(yàn)證的元素,value 可以是字串或物件。
$(".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:類(lèi)型 Boolean,預(yù)設(shè) true,指定是否提交時(shí)驗(yàn)證。
$(".selector").validate({  
	onsubmit:false})
onfocusout:類(lèi)型 Boolean,預(yù)設(shè) true,指定是否在取得焦點(diǎn)時(shí)驗(yàn)證。
$(".selector").validate({   
	onfocusout:false})
onkeyup:類(lèi)型 Boolean,預(yù)設(shè) true,指定是否在敲擊鍵盤(pán)時(shí)驗(yàn)證。
$(".selector").validate({
   onkeyup:false})
onclick:類(lèi)型 Boolean,預(yù)設(shè) true,指定是否在滑鼠點(diǎn)擊時(shí)驗(yàn)證(一般驗(yàn)證 checkbox、radiobox)。
$(".selector").validate({
   onclick:false})
focusInvalid:類(lèi)型 Boolean,預(yù)設(shè) true。提交表單後,未通過(guò)驗(yàn)證的表單(第一個(gè)或提交先前獲得焦點(diǎn)的未通過(guò)驗(yàn)證的表單)會(huì)獲得焦點(diǎn)。
$(".selector").validate({
   focusInvalid:false})
focusCleanup:類(lèi)型 Boolean,預(yù)設(shè) false。當(dāng)未通過(guò)驗(yàn)證的元素獲得焦點(diǎn)時(shí),移除錯(cuò)誤提示(避免和 focusInvalid 一起使用)。
$(".selector").validate({
   focusCleanup:true})
errorClass:類(lèi)型 String,預(yù)設(shè) "error"。指定錯(cuò)誤提示的 css 類(lèi)別名,可以自訂錯(cuò)誤提示的樣式。
$(".selector").validate({ 
	errorClass:"invalid"})
errorElement:類(lèi)型 String,預(yù)設(shè) "label"。指定使用什麼標(biāo)籤標(biāo)記錯(cuò)誤。
$(".selector").validate
   errorElement:"em"})
wrapper:類(lèi)型 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)證的元素經(jīng)過(guò)驗(yàn)證後的動(dòng)作,如果跟一個(gè)字串,會(huì)當(dāng)作一個(gè) css 類(lèi),也可跟一個(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è)字母,範(fàn)圍是a-f,寫(xiě)法如下:

$.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 中寫(xiě):

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í)的寫(xiě)法。

如果只有一個(gè)參數(shù),直接寫(xiě),例如 af:"a",那麼 a 就是這個(gè)唯一的參數(shù),如果多個(gè)參數(shù),則寫(xiě)在 [] 裡,用逗號(hào)分開(kāi)。

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>




# 繼續(xù)學(xué)習(xí)
||
<!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() { // 在鍵盤(pán)按下并釋放及提交后驗(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">我樂(lè)意接收新信息</label> <input type="checkbox" class="checkbox" id="newsletter" name="newsletter"> </p> <fieldset id="newsletter_topics"> <legend>主題 (至少選擇兩個(gè)) - 注意:如果沒(méi)有勾選“我樂(lè)意接收新信息”以下選項(xiàng)會(huì)隱藏,但我們這里作為演示讓它可見(jiàn)</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>
提交重置程式碼
<tfoot id="ptmah"><fieldset id="ptmah"></fieldset></tfoot>
      • <meter id="ptmah"><strike id="ptmah"></strike></meter>
        <kbd id="ptmah"><font id="ptmah"><form id="ptmah"></form></font></kbd>
      • 描述#程式碼