How can I disable a form's submit button if there are DataAnnotation validation errors?

老子叫甜甜 提交于 2019-12-14 02:30:08

问题


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.

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


回答1:


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);

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

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.

Edit: The above answer will only work for MVC3 and unobtrusive validation.

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

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


来源:https://stackoverflow.com/questions/7066278/how-can-i-disable-a-forms-submit-button-if-there-are-dataannotation-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!