2009-11-18 27 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);