如何禁用表单的提交按钮,如果有DataAnnotation验证错误? [英] How can I disable a form's submit button if there are DataAnnotation validation errors?

查看:210
本文介绍了如何禁用表单的提交按钮,如果有DataAnnotation验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试结合的形式所有输入的变化事件,并检查,看看是否有任何页面上的验证消息。问题是,似乎验证chan​​ge事件之后发生,所以我检查错误页面上显示之前。我正在寻找一些方法来运行我的脚本在客户端验证发生之后。

I've attempted binding to the change event of all inputs in the form, and checked to see if there are any validation messages on the page. The problem is that validation seems to occur after the change event, so I am checking before the errors appear on the page. I'm looking for some way to run my script after the client-side validation takes place.

我使用MVC 2 DataAnnotation我的虚拟机属性。

I'm using MVC 2 with DataAnnotation attributes on my VM.

推荐答案

这里的东西我只是砍死一起封装了原始的 parseElement invalidHandler 功能,让您可以添加自己的逻辑。

Here's something I just hacked together that wraps the original parseElement and invalidHandler functions, allowing you to add your own logic.

(function($) {
    $.validator.unobtrusive.parseElement = (function (original) {
        return function (element, skipAttach) {
            original.call(this, element, skipAttach);
            var form = $(element).parents("form:first")[0];
            var validationInfo = $(form).data('unobtrusiveValidation');
            if (validationInfo) {
                var handler = validationInfo.options.invalidHandler;
                var newhandler = function () {
                    console.log('Here is where you can do additional handling');
                    handler.call(this);
                };
                validationInfo.options.invalidHandler = $.proxy(newhandler, form);
            } else {
                // this didn't work.
            }
        }
    })($.validator.unobtrusive.parseElement);
})(jQuery);

通知,不过,这是一个直接函数,而不是jQuery函数相当于document.onload

Notice, though, that this is an immediate function, not the jQuery function which is equivalent to document.onload.

这是替换的的 $。validator.unobtrusive.parseElement 与调用原来,确保 validationInfo.options.invalidHandler 应用于父窗体,然后允许您将与 newhandler 函数处理。

This is replacing the $.validator.unobtrusive.parseElement with a new function that calls the original to ensure the validationInfo.options.invalidHandler is applied to the parent form, which then allows you to wrap that handler with the newhandler function.

修改:
以上回答将只MVC3和不显眼的审定工作。

要与 $进行一些额外的功能。验证当表单无效...

To perform some additional functionality with $.validator when the form is invalid...

$('form:first').bind("invalid-form.validate", function () { 
    alert("invalid!"); 
 });

这篇关于如何禁用表单的提交按钮,如果有DataAnnotation验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆