jQuery Validate

jQuery Validate

jQuery Validate 外掛為表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定製選項,滿足應用程式各種需求。該外掛捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫使用者自定義方法的 API。所有的捆綁方法預設使用英語作為錯誤資訊,且已翻譯成其他 37 種語言。

該外掛是由 J?rn Zaefferer 編寫和維護的,他是 jQuery 團隊的一名成員,是 jQuery UI 團隊的主要開發人員,是 QUnit 的維護人員。該外掛在 2006 年 jQuery 早期的時候就已經開始出現,並一直更新至今。目前版本是 1.14.0

訪問 jQuery Validate 官網,下載最新版的 jQuery Validate 外掛。

入門教學提供的 1.14.0 版本下載地址:http://static.itread01.com/download/jquery-validation-1.14.0.zip

匯入 js 庫(使用入門教學提供的CDN)

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

預設校驗規則

序號 規則 描述
1 required:true 必須輸入的欄位。
2 remote:"check.php" 使用 ajax 方法呼叫 check.php 驗證輸入值。
3 email:true 必須輸入正確格式的電子郵件。
4 url:true 必須輸入正確格式的網址。
5 date:true 必須輸入正確格式的日期。日期校驗 ie6 出錯,慎用。
6 dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗證格式,不驗證有效性。
7 number:true 必須輸入合法的數字(負數,小數)。
8 digits:true 必須輸入整數。
9 creditcard: 必須輸入合法的信用卡號。
10 equalTo:"#field" 輸入值必須和 #field 相同。
11 accept: 輸入擁有合法字尾名的字串(上傳檔案的字尾)。
12 maxlength:5 輸入長度最多是 5 的字串(漢字算一個字元)。
13 minlength:10 輸入長度最小是 10 的字串(漢字算一個字元)。
14 rangelength:[5,10] 輸入長度必須介於 5 和 10 之間的字串(漢字算一個字元)。
15 range:[5,10] 輸入值必須介於 5 和 10 之間。
16 max:5 輸入值不能大於 5。
17 min:10 輸入值不能小於 10。

預設提示

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,內容如下:

(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} 的數值")
});

}));

你可以將該本地化資訊檔案 dist/localization/messages_zh.js 引入到頁面:

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

使用方式

1、將校驗規則寫到控制元件中

<script src="http://static.itread01.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.itread01.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.itread01.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().ready(function() {
    $("#commentForm").validate();
});
</script>

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>輸入您的名字,郵箱,URL,備註。</legend>
    <p>
      <label for="cname">Name (必需, 最小兩個字母)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (必需)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (可選)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">備註 (必需)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="https://www.itread01.com/jquery/Submit">
    </p>
  </fieldset>
</form>

嘗試一下 ?

2、將校驗規則寫到 js 程式碼中

$().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 處,如果某個控制元件沒有 message,將呼叫預設的資訊

<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="https://www.itread01.com/jquery/marketflash" name="topic">Marketflash
      </label>
      <label for="topic_fuzz">
        <input type="checkbox" id="topic_fuzz" value="https://www.itread01.com/jquery/fuzz" name="topic">Latest fuzz
      </label>
      <label for="topic_digester">
        <input type="checkbox" id="topic_digester" value="https://www.itread01.com/jquery/digester" name="topic">Mailing list digester
      </label>
      <label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
    </fieldset>
    <p>
      <input class="submit" type="submit" value="https://www.itread01.com/jquery/提交">
    </p>
  </fieldset>
</form>

嘗試一下 ?

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

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

常用方法及注意問題

1、用其他方式替代預設的 SUBMIT

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

使用 ajax 方式

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

可以設定 validate 的預設值,寫法如下:

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

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

2、debug,只驗證不提交表單

如果這個引數為true,那麼表單不會提交,只進行檢查,除錯時十分方便。

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

如果一個頁面中有多個表單都想設定成為 debug,則使用:

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

3、ignore:忽略某些元素不驗證

ignore: ".ignore"

4、更改錯誤資訊顯示的位置

errorPlacement:Callback

指明錯誤放置的位置,預設情況是:error.appendTo(element.parent());即把錯誤資訊放在驗證的元素後面。

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

例項

<p>將錯誤資訊放在 label 元素後並使用 span 元素包裹它</p>

<form method="get" class="cmxform" id="form1" action="">
  <fieldset>
    <legend>Login Form</legend>
    <p>
      <label for="user">Username</label>
      <input id="user" name="user" required minlength="3">
    </p>
    <p>
      <label for="password">Password</label>
      <input id="password" type="password" maxlength="12" name="password" required minlength="5">
    </p>
    <p>
      <input class="submit" type="submit" value="https://www.itread01.com/jquery/Login">
    </p>
  </fieldset>
</form>

嘗試一下 ?

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

引數 型別 描述 預設值
errorClass String 指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。 "error"
errorElement String 用什麼標籤標記錯誤,預設是 label,可以改成 em。 "label"
errorContainer Selector 顯示或者隱藏驗證資訊,可以自動實現有錯誤資訊出現時把容器屬性變為顯示,無錯誤時隱藏,用處不大。
errorContainer: "#messageBox1, #messageBox2"
errorLabelContainer Selector 把錯誤資訊統一放在一個容器裡面。
wrapper String 用什麼標籤再把上邊的 errorELement 包起來。

一般這三個屬性同時使用,實現在一個容器內顯示所有錯誤提示的功能,並且沒有資訊時自動隱藏。

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

5、更改錯誤資訊顯示的樣式

設定錯誤提示的樣式,可以增加圖示顯示,在該系統中已經建立了一個 validation.css,專門用於維護校驗檔案的樣式。

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、每個欄位驗證通過執行函式

success:String,Callback

要驗證的元素通過驗證後的動作,如果跟一個字串,會當作一個 css 類,也可跟一個函式。

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

新增 "valid" 到驗證元素,在 CSS 中定義的樣式 <style>label.valid {}</style>。

success: "valid"

7、驗證的觸發方式修改

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

觸發方式 型別 描述 預設值
onsubmit Boolean 提交時驗證。設定為 false 就用其他方法去驗證。 true
onfocusout Boolean 失去焦點時驗證(不包括複選框/單選按鈕)。 true
onkeyup Boolean 在 keyup 時驗證。 true
onclick Boolean 在點選複選框和單選按鈕時驗證。 true
focusInvalid Boolean 提交表單後,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 true
focusCleanup Boolean 如果是 true 那麼當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 false
// 重置表單
$().ready(function() {
 var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
    $("#reset").click(function() {
        validator.resetForm();
    });

});

8、非同步驗證

remote:URL

使用 ajax 方式進行驗證,預設會提交當前驗證的值到遠端地址,如果需要提交其他的值,可以使用 data 選項。

remote: "check-email.php"
remote: {
    url: "check-email.php",     //後臺處理程式
    type: "post",               //資料傳送方式
    dataType: "json",           //接受資料格式   
    data: {                     //要傳遞的資料
        username: function() {
            return $("#username").val();
        }
    }
}

遠端地址只能輸出 "true" 或 "false",不能有其他輸出。

9、新增自定義校驗

addMethod:name, method, message

自定義驗證方法

// 中文字兩個位元組
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));
}, "請正確填寫您的郵政編碼");

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

注意:在 messages_cn.js 檔案中新增:isZipCode: "只能包括中文字、英文字母、數字和下劃線"。呼叫前要新增對 additional-methods.js 檔案的引用。

10、radio 和 checkbox、select 的驗證

radio 的 required 表示必須選中一個。

<input  type="radio" id="gender_male" value="https://www.itread01.com/jquery/m" name="gender" required />
<input  type="radio" id="gender_female" value="https://www.itread01.com/jquery/f" name="gender"/>

checkbox 的 required 表示必須選中。

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

checkbox 的 minlength 表示必須選中的最小個數,maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<input type="checkbox" class="checkbox" id="spam_email" value="https://www.itread01.com/jquery/email" name="spam[]" required minlength="2" />
<input type="checkbox" class="checkbox" id="spam_phone" value="https://www.itread01.com/jquery/phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="https://www.itread01.com/jquery/mail" name="spam[]" />

select 的 required 表示選中的 value 不能為空。

<select id="jungle" name="jungle" title="Please select something!" required>
    <option value=""></option>
    <option value="https://www.itread01.com/jquery/1">Buga</option>
    <option value="https://www.itread01.com/jquery/2">Baga</option>
    <option value="https://www.itread01.com/jquery/3">Oi</option>
</select>

select 的 minlength 表示選中的最小個數(可多選的 select),maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
    <option value="https://www.itread01.com/jquery/b">Banana</option>
    <option vhttps://www.itread01.com/jquery/alue="a">Apple</option>
    <option value="https://www.itread01.com/jquery/p">Peach</option>
    <option value="https://www.itread01.com/jquery/t">Turtle</option>
</select>

jQuery.validate 中文 API

名稱 返回型別 描述
validate(options) Validator 驗證所選的 FORM。
valid() Boolean 檢查是否驗證通過。
rules() Options 返回元素的驗證規則。
rules("add",rules) Options 增加驗證規則。
rules("remove",rules) Options 刪除驗證規則。
removeAttrs(attributes) Options 刪除特殊屬性並且返回它們。
自定義選擇器
:blank Validator 沒有值的篩選器。
:filled Array <Element> 有值的篩選器。
:unchecked Array <Element> 沒選擇的元素的篩選器。
實用工具
jQuery.format(template,argument,argumentN...) String 用引數代替模板中的 {n}。

Validator

validate 方法返回一個 Validator 物件。Validator 物件有很多方法可以用來引發校驗程式或者改變 form 的內容,下面列出幾個常用的方法。

名稱 返回型別 描述
form() Boolean 驗證 form 返回成功還是失敗。
element(element) Boolean 驗證單個元素是成功還是失敗。
resetForm() undefined 把前面驗證的 FORM 恢復到驗證前原來的狀態。
showErrors(errors) undefined 顯示特定的錯誤資訊。
Validator 函式
setDefaults(defaults) undefined 改變預設的設定。
addMethod(name,method,message) undefined 新增一個新的驗證方法。必須包括一個獨一無二的名字,一個 JAVASCRIPT 的方法和一個預設的資訊。
addClassRules(name,rules) undefined 增加組合驗證型別,在一個類裡面用多種驗證方法時比較有用。
addClassRules(rules) undefined 增加組合驗證型別,在一個類裡面用多種驗證方法時比較有用。這個是同時加多個驗證方法。

內建驗證方式

名稱 返回型別 描述
required() Boolean 必填驗證元素。
required(dependency-expression) Boolean 必填元素依賴於表示式的結果。
required(dependency-callback) Boolean 必填元素依賴於回撥函式的結果。
remote(url) Boolean 請求遠端校驗。url 通常是一個遠端呼叫方法。
minlength(length) Boolean 設定最小長度。
maxlength(length) Boolean 設定最大長度。
rangelength(range) Boolean 設定一個長度範圍 [min,max]。
min(value) Boolean 設定最小值。
max(value) Boolean 設定最大值。
email() Boolean 驗證電子郵箱格式。
range(range) Boolean 設定值的範圍。
url() Boolean 驗證 URL 格式。
date() Boolean 驗證日期格式(類似 30/30/2008 的格式,不驗證日期準確性只驗證格式)。
dateISO() Boolean 驗證 ISO 型別的日期格式。
dateDE() Boolean 驗證德式的日期格式(29.04.1994 或 1.1.2006)。
number() Boolean 驗證十進位制數字(包括小數的)。
digits() Boolean 驗證整數。
creditcard() Boolean 驗證信用卡號。
accept(extension) Boolean 驗證相同字尾名的字串。
equalTo(other) Boolean 驗證兩個輸入框的內容是否相同。
phoneUS() Boolean 驗證美式的電話號碼。

validate ()的可選項

描述 程式碼
debug:進行除錯模式(表單不提交)。
$(".selector").validate
({
    debug:true
})
把除錯設定為預設。
$.validator.setDefaults({
    debug:true
})
submitHandler:通過驗證後執行的函式,裡面要加上表單提交的函式,否則表單不會提交。
$(".selector").validate({
    submitHandler:function(form) {
        $(form).ajaxSubmit();
    }
})
ignore:對某些元素不進行驗證。
$("#myform").validate({
    ignore:".ignore"
})
rules:自定義規則,key:value 的形式,key 是要驗證的元素,value 可以是字串或物件。
$(".selector").validate({
    rules:{
        name:"required",
        email:{
            required:true,
            email:true
        }
    }
})
messages:自定義的提示資訊,key:value 的形式,key 是要驗證的元素,value 可以是字串或函式。
$(".selector").validate({
    rules:{
        name:"required",
        email:{
            required:true,
            email:true
        }
    },
    messages:{
        name:"Name不能為空",
        email:{       
            required:"E-mail不能為空",
            email:"E-mail地址不正確"
        }
    }
})
groups:對一組元素的驗證,用一個錯誤提示,用 errorPlacement 控制把出錯資訊放在哪裡。
$("#myform").validate({
    groups:{
        username:"fname 
        lname"
    },
    errorPlacement:function(error,element) {
        if (element.attr("name") == "fname" || element.attr("name") == "lname")   
            error.insertAfter("#lastname");
        else    
            error.insertAfter(element);
    },
   debug:true
})
OnSubmit:型別 Boolean,預設 true,指定是否提交時驗證。
$(".selector").validate({  
    onsubmit:false
})
onfocusout:型別 Boolean,預設 true,指定是否在獲取焦點時驗證。
$(".selector").validate({   
    onfocusout:false
})
onkeyup:型別 Boolean,預設 true,指定是否在敲擊鍵盤時驗證。
$(".selector").validate({
   onkeyup:false
})
onclick:型別 Boolean,預設 true,指定是否在滑鼠點選時驗證(一般驗證 checkbox、radiobox)。
$(".selector").validate({
   onclick:false
})
focusInvalid:型別 Boolean,預設 true。提交表單後,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。
$(".selector").validate({
   focusInvalid:false
})
focusCleanup:型別 Boolean,預設 false。當未通過驗證的元素獲得焦點時,移除錯誤提示(避免和 focusInvalid 一起使用)。
$(".selector").validate({
   focusCleanup:true
})
errorClass:型別 String,預設 "error"。指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。
$(".selector").validate({ 
    errorClass:"invalid"
})
errorElement:型別 String,預設 "label"。指定使用什麼標籤標記錯誤。
$(".selector").validate
   errorElement:"em"
})
wrapper:型別 String,指定使用什麼標籤再把上邊的 errorELement 包起來。
$(".selector").validate({
   wrapper:"li"
})
errorLabelContainer:型別 Selector,把錯誤資訊統一放在一個容器裡面。
$("#myform").validate({   
    errorLabelContainer:"#messageBox",
    wrapper:"li",
    submitHandler:function() { 
        alert("Submitted!") 
    }
})
showErrors:跟一個函式,可以顯示總共有多少個未通過驗證的元素。
$(".selector").validate({  
    showErrors:function(errorMap,errorList) {
        $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
        this.defaultShowErrors();
    }
})
errorPlacement:跟一個函式,可以自定義錯誤放到哪裡。
$("#myform").validate({  
    errorPlacement:function(error,element) {  
        error.appendTo(element.parent("td").next("td"));
   },
   debug:true
})
success:要驗證的元素通過驗證後的動作,如果跟一個字串,會當作一個 css 類,也可跟一個函式。
$("#myform").validate({        
    success:"valid",
        submitHandler:function() { 
            alert("Submitted!") 
        }
})
highlight:可以給未通過驗證的元素加效果、閃爍等。

addMethod(name,method,message)方法

引數 name 是新增的方法的名字。

引數 method 是一個函式,接收三個引數 (value,element,param) 。
value 是元素的值,element 是元素本身,param 是引數。

我們可以用 addMethod 來新增除內建的 Validation 方法之外的驗證方法。比如有一個欄位,只能輸一個字母,範圍是 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;
    }
},"必須是一個字母,且a-f");

如果有個表單欄位的 name="username",則在 rules 中寫:

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

addMethod 的第一個引數,是新增的驗證方法的名字,這時是 af。
addMethod 的第三個引數,是自定義的錯誤提示,這裡的提示為:"必須是一個字母,且a-f"。
addMethod 的第二個引數,是一個函式,這個比較重要,決定了用這個驗證方法時的寫法。

如果只有一個引數,直接寫,比如 af:"a",那麼 a 就是這個唯一的引數,如果多個引數,則寫在 [] 裡,用逗號分開。

meta String 方式

$("#myform").validate({

   meta:"validate",

   submitHandler:function() { 
alert("Submitted!") }

})
<script type="text/javascript" 
src="https://www.itread01.com/jquery/js/jquery.metadata.js"></script>

<script type="text/javascript" 
src="https://www.itread01.com/jquery/js/jquery.validate.js"></script>

<form id="myform">

  <input type="text" 
name="email" class="{validate:{ required:true,email:true }}" />

  <input type="submit" 
value="https://www.itread01.com/jquery/Submit" />

</form>

例項演示

虛構的例項

  • 錯誤訊息容器
  • 自定義訊息作為元素資料
  • radio(單選按鈕)、checkbox(複選按鈕)和 select(下拉框)
  • 與表單(Form)外掛的互動(AJAX 提交)
  • 自定義方法和訊息顯示
  • 動態表單
  • 使用 jQuery UI Themeroller 定義表單樣式
  • TinyMCE - 一個輕量級的基於瀏覽器的所見即所得編輯器
  • 檔案輸入框
  • jQuery Mobile 表單驗證

現實世界的例項

  • Milk 登錄檔單
  • Marketo 登錄檔單
  • 房屋買賣摺疊面板表單
  • 遠端 CAPTCHA(驗證碼)驗證

例項下載