How to add a 'submitHandler' function when using jQuery Unobtrusive Validation?

前端 未结 5 2008
-上瘾入骨i
-上瘾入骨i 2020-11-27 13:31

I\'m validating a form using the new unobtrusive validation features in ASP.NET MVC 3.

So there is no code that I have written to setup jQuery validate to start vali

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 14:21

    I based this on the original answer, which didn't work for me. I guess things have changed in jQuery.

    As usual, take this code and add copious error checking :D I use similar code to prevent double-submits on our forms, and it works fine in IE8+ (as of mvc4 and jquery 1.8.x).

    $("#myFormId").confirmAfterValidation();
    
    // placed outside of a $(function(){ scope
    jQuery.fn.confirmAfterValidation = function () {
        // do error checking first.  should be null if no handler already
        $(this).data('validator').settings.submitHandler = confirmValidForm;
    };
    
    function confirmValidForm(form) {
        var validator = $(this);
        var f = $(form);
        if (confirm("really really submit?")) {
            // unbind so our handler doesn't get called again, and submit
            f.unbind('submit').submit();
        }
            // return value is _ignored_ by jquery.validate, so we have to set
            // the flag on the validator itself, but it should cancel the submit
            // anyway if we have a submitHandler
            validator.cancelSubmit = true;
        }
    }
    

提交回复
热议问题