jQuery Validation plugin: disable validation for specified submit buttons

后端 未结 12 756
故里飘歌
故里飘歌 2020-11-22 16:14

I have a form with multiple fields that I\'m validating (some with methods added for custom validation) with Jörn Zaeffere\'s excellent jQuery Validation plugin. How do you

12条回答
  •  执笔经年
    2020-11-22 16:42

    (Extension of @lepe's and @redsquare answer for ASP.NET MVC + jquery.validate.unobtrusive.js)


    The jquery validation plugin (not the Microsoft unobtrusive one) allows you to put a .cancel class on your submit button to bypass validation completely (as shown in accepted answer).

     To skip validation while still using a submit-button, add a class="cancel" to that input.
    
      
      
    

    (don't confuse this with type='reset' which is something completely different)

    Unfortunately the jquery.validation.unobtrusive.js validation handling (ASP.NET MVC) code kinda screws up the jquery.validate plugin's default behavior.

    This is what I came up with to allow you to put .cancel on the submit button as shown above. If Microsoft ever 'fixes' this then you can just remvoe this code.

        // restore behavior of .cancel from jquery validate to allow submit button 
        // to automatically bypass all jquery validation
        $(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)
        {
            // find parent form, cancel validation and submit it
            // cancelSubmit just prevents jQuery validation from kicking in
            $(this).closest('form').data("validator").cancelSubmit = true;
            $(this).closest('form').submit();
            return false;
        });
    

    Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and seeing a server generated page with errors. You'll need to bypass validation on the server side by some other means - this just allows the form to be submitted client side without errors (the alternative would be adding .ignore attributes to everything in your form).

    (Note: you may need to add button to the selector if you're using buttons to submit)

提交回复
热议问题