jQuery - Getting custom validation methods to trigger
If I've added a custom validation method to my form, how can I get it to trigger prior to submit?
I'm not decorating my form fields but I thought that adding the new method to my rules section would trigger the method but it doesn't work.
$.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
}
});
I'd like have the validation get triggered when the 'submit' button is pressed.
However, if I add the validation cla开发者_开发百科ss name to any form field except the submit button, this rule gets triggered. Just can't seem to get it to be triggered just prior to submit..
I haven't used the addMethod
function but I can suggest you this:
$.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
}
});
wrap your code in:
$(function(){
//your code goes here
});
this will attach validation events on-page-load.
Call .valid()
to trigger the validation:
$("#myFormId").valid();
I think you're looking for 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
}
});
You are missing something. rules should look like this.
rules: {
"elemId": {
required: true,
myCustomValidation: true
}
},
I recommend using the native $.validator.addMethod to bind the custom method. After that, just call jquery's blur()
on the element
to trigger validation.
Due to a race condition that I suspect exists in jQuery Validate, I had to spin wait in order to avoid getting a blank error message when I programmatically invoke validation
//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);
精彩评论