正如 jQuery/Validation 文档所说,你可以使用无效处理程序当提交无效表单时做出反应。
但由于 MVC 不显眼的验证会实例化验证本身,因此您必须稍后挂钩此事件。
使用与 jQuery/Validation 完全相同的机制:您可以将代码绑定到表单元素自定义事件'无效表单.validate',witch对应的是invalidHandler!
$(document).ready(function() {
$('#myform').bind('invalid-form.validate',function(){
alert('invalid form!');
});
});
给你的表单一个 id 使用:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform" })) {
}
Update:
An alternative way to get the existing validation object is calling validate() on the form. If a validator for this form was already created, it will be returned:
编辑:初始化发生后,更改.settings.invalidHandler
绑定已经太晚了。因此,除非您重新初始化验证器,否则以下代码片段将不再起作用。
$(document).ready(function() {
var existingValdiation = $("#myform").validate();
//the settings property corresponds to the options parameter
existingValdiation.settings.invalidHandler = function (form) {
alert('invalid form!');
};
// not recommended:
// re-init would bind settings.invalidHandler to 'invalid-form.validate'
// existingValdiation.init();
});