Skip to content

jQuery validation 的 addMethod

jQueryValidation 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 就不會偵測到。

這樣很「正路」吧?但花了不少時間去看才知道。

Jacky27 Mar 2008 2:50 am 寫關於電腦

Tags: , , , , 。 [ 永久連結 | 引用 | 回應 RSS ]

6 個留言

  1. 1. 錯字
    寫發 => 寫法

    2. validation 網址連不上

  2. 謝更正
    Validation 的網址我連得上啊

  3. 今天我在一个blog上看到jQuery的这个插件,真的很不错,以前我都是自己一个函数一个函数的写判断啊~

  4. Richard 寫於 17 Feb 2011 10:13 am

    請教一個問題
    以下網址為一個三欄的表單頁面
    http://www.hobbies.com.tw/006_accede/01-accede_Activity_high_mountain_4.html
    希望以jquery validation來驗證
    條件為只要擇其一填寫資料即可
    請問該怎麼寫判斷呢

  5. You may try to use depedency-callback http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression

  6. Richard 寫於 17 Feb 2011 10:46 am

    謝謝指教 我試著瞭解看看

發表回應