我试图从showErrors
函数中调用jQuery验证submitHandler
函数,而不必像这样保存验证器对象:
var validator = $( "#myshowErrors" ).validate();
validator.showErrors({
"firstname": "I know that your firstname is Pete, Pete!"
});
有没有办法从submitHandler
方法中获取验证器对象,如下所示:
$( "#myshowErrors" ).validate({
submitHandler : function(form) {
$(form).ajaxSubmit({
success : function(result) {
var validator = // Get validator here somehow?
validator.showErrors(result.fieldErrors);
}
});
}
});
通过这种方式,我希望我可以在整个项目的多个地方使用相同的submitHandler
方法。
答案 0 :(得分:19)
Validator对象存储在表单元素数据中:
var validator = $.data( form, "validator");
修改强>
实际上验证器也应该存储在this
:
$( "#myshowErrors" ).validate({
submitHandler : function(form) {
var validator = this;
$(form).ajaxSubmit({
success : function(result) {
validator.showErrors(result.fieldErrors);
}
});
}
});