jQuery 的 Validation plugins 是很強大的,基本上可以滿足各種需要。剛剛被一個小問題困擾了好一陣子,特此記下。我寫了類似的東西:
<div id="error" style="display:none"><ul></ul></div>
<form id="form1">
<input type="hidden" name="fff" id="fff" value="" class="special" />
</form>
$.validator.addMethod("special", function(value, element, params){
//validate….
return result;
}, "This is a special checking");
$(document).ready(function(){
$("#form").validate({
messages:{ fff: {special: "This is a special checking!"} },
errorContainer: "#error",
errorLabelContainer: "#error ul",
wrapper: "li"
});
});
結果怎樣也出不到那個自訂的 validation rule,苦苦深研追踪 source code 後才發現,問題在於 addMethod 裏的 method 參數問題,而正確的寫法是:
$.validator.addMethod("special", function(){
//validate...
return result;
}, "This is a special checking");
那個 method 的參數數量如果大於 3,plugins 會認為你所加的是有參數的 validation,即在 element class 可能是 {special:abc} 之類,所以當看到 input 裏只是 special 就不會偵測到。
這樣很「正路」吧?但花了不少時間去看才知道。