2009-11-18 32 views
4

如果我已經爲自己的表單添加了自定義驗證方法,那麼在提交之前如何才能觸發它?jQuery - 獲取自定義驗證方法來觸發

我不裝飾我的表單字段,但我認爲將新方法添加到我的規則部分會觸發該方法,但它不起作用。

$.validator.addMethod('myCustomValidation', function (data) 
{ 
    // do some work here 
    return myValidationResult; 

}, 'Please respond.'); 


$("#myFormId").validate({   
    rules: { 
     "myCustomValidation": {required: true} 
    }, 
    messages: { 
     "myCustomValidation": { 
      required: "Enter some information before proceeding",   
     } 
    }, 
    submitHandler: function(form) 
    { 
     // do the work to submit this form 
    } 
}); 

我想驗證按'submit'按鈕時觸發。

但是,如果我將驗證類名稱添加到除submit按鈕之外的任何表單字段,則會觸發此規則。似乎無法得到它的觸發提交前夕..

+0

我認爲編輯工作這包括包含您要驗證的表單的HTML片段將有所幫助。 – jamiebarrow 2010-10-08 13:00:48

回答

0

包裝你的代碼:

$(function(){ 
    //your code goes here 
}); 

這將附加在頁面加載驗證事件。

+0

它已經被封裝 - 更多的是驗證不會在提交表單之前觸發。 – 2009-11-18 18:12:59

1

我沒有使用過addMethod功能,但我可以建議你:

$.validator.methods.myCustomValidation = function(value, element, param) { 
    // Perform custom validation and return true or false 
    return value === '' || /^([0-9]{10})$/.test(value); 
}; 


$("#myFormId").validate({   
    rules: { 
     myElement: { 
      myCustomValidation: true 
     } 
    }, 
    messages: { 
     myElement: { 
      myCustomValidation: "Enter some information before proceeding" 
     } 
    }, 
    submitHandler: function(form) 
    { 
     // do the work to submit this form 
    } 
}); 
+0

我試過這個,但它似乎沒有工作。我想要做的是確保在調用submitHandler之前觸發驗證。我認爲有關元素的規則(在類名中指定)會觸發驗證。也許我不太理解文檔。 – 2009-11-18 20:51:45

0

你失去了一些東西。規則應該看起來像這樣。

rules: { 
    "elemId": { 
     required: true, 
     myCustomValidation: true 
    } 
}, 
0

呼叫.valid()觸發驗證:

$("#myFormId").valid(); 
+0

你可以在submitHandler裏面調用'valid'嗎? – 2009-11-18 19:51:11

0

我認爲你正在尋找addClassRules

$.validator.addMethod('myCustomValidation', function (data) 
{ 
    // do some work here 
    return myValidationResult; 

}, 'Please respond.'); 

$.validator.addClassRules({ 
    myCustomValidation: { myCustomValidation: true, required: true } 
}); 

$("#myFormId").validate({   
    messages: { 
     "myCustomValidation": { 
      required: "Enter some information before proceeding",   
     } 
    }, 
    submitHandler: function(form) 
    { 
     // do the work to submit this form 
    } 
}); 
0

我推薦使用本地$.validator.addMethod綁定自定義的方法。之後,只需撥打element上的jquery的blur()即可觸發驗證。

由於我懷疑存在於jQuery驗證的競爭條件,我不得不自旋等待,以避免收到一個空白的錯誤消息時我編程方式調用驗證

  //after binding custom validation method 
      if($("#myElement").length){//add any checks you need 
       var millisecondsToWait = 500; 
       //Spin because it works 
       setTimeout(function() { 
        $("#myElement").blur(); 
        //$("#myElement").valid();//or this 
       }, millisecondsToWait);