jquery validate驗證規則重用

當多個控件驗證規則相同時,如何避免冗餘代碼並應用相同規則呢?javascript

【1st way. addMethod+addClassRules】html

場景:維護學生檔案時須要維護父母、監護人、緊急聯繫人的身份證號碼,此時頁面4個input都須要身份證號碼驗證;java

解決:jquery

[1].在四個input的class上增長idcard;ide

[2].定義驗證規則idCard,對樣式爲idcard的控件附加身份證驗證;
ui

$.validator.addMethod("idCard", $.validator.methods.card, "身份證號不正確");
$.validator.addClassRules("idcard", {idCard : true});
this


參考自動動我試試spa

Whenever you have multiple fields with the same rules and messages, refactoring those can reduce a lot of duplication. Using addMethod and addClassRules are most effective for that.code

Let's consider an example where you have ten customer fields, each required and with a minlength of 2. You need custom messages for both rules. To avoid having to specify those rules and messages again and again, we can alias existing methods with different messages and group them into a single class:orm

// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required, "Customer name required");

// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength,

// leverage parameter replacement for minlength, {0} gets replaced with 2
$.validator.format("Customer name must have at least {0} characters"));

// combine them both, including the parameter for minlength
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });


With that in place, we can add a class customer to all customer fields and be done with it:

 <input name="customer1" class="customer">
 <input name="customer2" class="customer">
 <input name="customer3" class="customer">

You can also reuse existing methods inside other custom methods, to reuse certain implementations. For example, if you're writing a custom method for validating email addresses inside a single field, you could call the existing email method for each email:
jQuery.validator.methods.email.call(this, email, element)
相關文章
相關標籤/搜索