jQuery Validation plugin: disable validation for specified submit buttons

JqueryJquery Validate

Jquery Problem Overview


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 circumvent validation with specified submit controls (in other words, fire validation with some submit inputs, but do not fire validation with others)? This would be similar to ValidationGroups with standard ASP.NET validator controls.

My situation:

It's with ASP.NET WebForms, but you can ignore that if you wish. However, I am using the validation more as a "recommendation": in other words, when the form is submitted, validation fires but instead of a "required" message displaying, a "recommendation" shows that says something along the line of "you missed the following fields.... do you wish to proceed anyways?" At that point in the error container there's another submit button now visible that can be pressed which would ignore the validation and submit anyways. How to circumvent the forms .validate() for this button control and still post?

The Buy and Sell a House sample at http://jquery.bassistance.de/validate/demo/multipart/ allows for this in order to hit the previous links, but it does so through creating custom methods and adding it to the validator. I would prefer to not have to create custom methods duplicating functionality already in the validation plugin.

The following is a shortened version of the immediately applicable script that I've got right now:

var container = $("#<%= Form.ClientID %> div.validationSuggestion");
        
$('#<%= Form.ClientID %>').validate({          
    errorContainer: container,
    errorLabelContainer: $("ul",container),
    rules: {
        <%= YesNo.UniqueID %>: { required: true },
        <%= ShortText.UniqueID %>: { required: true } // etc.

    },
    messages: {
        <%= YesNo.UniqueID %>: 'A message.',
        <%= ShortText.UniqueID %>: 'Another message.' // etc.
    },
    highlight: function(element, errorClass) {
        $(element).addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass("valid");
    },
    unhighlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
        $(element.form).find("label[for=" + element.id + "]").addClass("valid");
    },
    wrapper: 'li'
}); 

Jquery Solutions


Solution 1 - Jquery

You can add a CSS class of cancel to a submit button to suppress the validation

e.g

<input class="cancel" type="submit" value="Save" />

See the jQuery Validator documentation of this feature here: Skipping validation on submit


EDIT:

The above technique has been deprecated and replaced with the formnovalidate attribute.

<input formnovalidate="formnovalidate" type="submit" value="Save" />

Solution 2 - Jquery

Other (undocumented) way to do it, is to call:

$("form").validate().cancelSubmit = true;

on the click event of the button (for example).

Solution 3 - Jquery

Yet another (dynamic) way:

$("form").validate().settings.ignore = "*";

And to re-enable it, we just set back the default value:

$("form").validate().settings.ignore = ":hidden";

Source: https://github.com/jzaefferer/jquery-validation/issues/725#issuecomment-17601443

Solution 4 - Jquery

Add formnovalidate attribute to input

    <input type="submit" name="go" value="Submit"> 
    <input type="submit" formnovalidate name="cancel" value="Cancel"> 

Adding class="cancel" is now deprecated

See docs for Skipping validation on submit on this link

Solution 5 - Jquery

You can use the onsubmit:false option (see documentation) when wiring up validation which will not validate on submission of the form. And then in your asp:button add an OnClientClick= $('#aspnetForm').valid(); to explicitly check if form is valid.

You could call this the opt-in model, instead of the opt-out described above.

Note, I am also using jquery validation with ASP.NET WebForms. There are some issues to navigate but once you get through them, the user experience is very good.

Solution 6 - Jquery

(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.

  <input type="submit" name="submit" value="Submit"/>
  <input type="submit" class="cancel" name="cancel" value="Cancel"/>

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

Solution 7 - Jquery

$("form").validate().settings.ignore = "*";

Or

$("form").validate().cancelSubmit = true;

But without success in a custom required validator. For call a submit dynamically, i have created a fake hidden submit button with this code:

var btn = form.children('input.cancel.fakeSubmitFormButton');
if (btn.length === 0) {
    btn = $('<input name="FakeCancelSubmitButton" class="cancel fakeSubmitFormButton hide" type="submit" formnovalidate value="FakeCancelSubmitButton" />');
    form.append(btn);
}
btn.click();

Now skip the validation correctly :)

Solution 8 - Jquery

This question is old, but I found another way around it is to use $('#formId')[0].submit(), which gets the dom element instead of the jQuery object, thus bypassing any validation hooks. This button submits the parent form that contains the input.

<input type='button' value='SubmitWithoutValidation' onclick='$(this).closest('form')[0].submit()'/>

Also, make sure you don't have any input's named "submit", or it overrides the function named submit.

Solution 9 - Jquery

I found that the most flexible way is to do use JQuery's:

event.preventDefault():

E.g. if instead of submitting I want to redirect, I can do:

$("#redirectButton").click(function( event ) {
	event.preventDefault();
	window.location.href='http://www.skip-submit.com';
});

or I can send the data to a different endpoint (e.g. if I want to change the action):

$("#saveButton").click(function( event ) {
	event.preventDefault();
    var postData = $('#myForm').serialize();
    var jqxhr = $.post('http://www.another-end-point.com', postData ,function() {
    }).done(function() {
		alert("Data sent!");
	}).fail(function(jqXHR, textStatus, errorThrown) {
		alert("Ooops, we have an error");
	})

Once you do 'event.preventDefault();' you bypass validation.

Solution 10 - Jquery

I have two button for form submission, button named save and exit bypasses the validation :

$('.save_exist').on('click', function (event) {
            $('#MyformID').removeData('validator');
            $('.form-control').removeClass('error');
            $('.form-control').removeClass('required');                
            $("#loanApplication").validate().cancelSubmit = true;
            $('#loanApplication').submit();
            event.preventDefault();
});

Solution 11 - Jquery

<button type="submit" formnovalidate="formnovalidate">submit</button>

also working

Solution 12 - Jquery

Here is the simplest version, hope it helps someone,

$('#cancel-button').click(function() {
    var $form = $(this).closest('form');
    $form.find('*[data-validation]').attr('data-validation', null);
    $form.get(0).submit();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTedView Question on Stackoverflow
Solution 1 - JqueryredsquareView Answer on Stackoverflow
Solution 2 - JquerylepeView Answer on Stackoverflow
Solution 3 - JqueryDaniel GarciaView Answer on Stackoverflow
Solution 4 - JqueryTastyCodeView Answer on Stackoverflow
Solution 5 - JqueryBrokeMyLegBikingView Answer on Stackoverflow
Solution 6 - JquerySimon_WeaverView Answer on Stackoverflow
Solution 7 - JqueryDavide CiarmielloView Answer on Stackoverflow
Solution 8 - Jquerybradlis7View Answer on Stackoverflow
Solution 9 - JqueryScott MayersView Answer on Stackoverflow
Solution 10 - JqueryBugfixerView Answer on Stackoverflow
Solution 11 - Jqueryuser3024034View Answer on Stackoverflow
Solution 12 - JqueryLucyView Answer on Stackoverflow