Reputation: 5406
Noticed the code of the submitHandler
was being used in several places, and tried to refactor it out.
var validator = $("#form_id").validate({
errorClass: "ui-state-error",
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
dataType: 'json',
success: function(entity) {
//dostuff
},
error: function(errors) {
validator.showErrors(errors);
}
});
}
});
I took the code above and extracted the submithandler to a function like so;
$("#generated_form_id").validate({
errorClass: "ui-state-error",
submitHandler: bindSubmitHandler(formId)
}
});
function bindSubmitHandler(formId){
return function(form) {
jQuery(form).ajaxSubmit({
dataType: 'json',
success: function(object) {
//do stuff
});
},
error: function(errors) {
validator.showErrors(errors); //throws an exception
}
});
}
}
This code throws an exception because the validator object is undefined.
My own reasoning which may be false has been as follows: I can't store the variable, because the forms are being created dynamically. One page could create ten of these forms using the same bindSubmitHandler
function.
I thought about the solution of getting the validator via the form, but couldn't find any such method in the validator API. If there is such a method, I could write something like $('#formid').getValidator().showErrors(errors);
Does anyone have an idea for a solution to this problem?
Upvotes: 1
Views: 88
Reputation: 160251
validate()
returns a validator.
Attach the validator to the form using .data()
, retrieve it bindSubmitHandler
.
Wouldn't you also want to pass in success
and possibly error
handlers as well, though?
Upvotes: 1