172

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'
}); 
Sparky
  • 98,165
  • 25
  • 199
  • 285
Ted
  • 7,122
  • 9
  • 50
  • 76
  • Also specify the keyword return at button, so that it won't navigate away http://technote.in/TechNote/Forums/AspnetReply.aspx?post_id=134 –  Jan 08 '11 at 05:59

12 Answers12

298

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" />
user489998
  • 4,473
  • 2
  • 29
  • 35
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 1
    Is it working with ?I added class="cancel" and it's not working. I'm using MVC2 with MicrosoftMvcValidation. Thank you. – VinnyG Dec 13 '10 at 22:56
  • 4
    @VinnyG - not used MicrosoftMvcValidation (and would never) - this is not the same as jquery validate. – redsquare Dec 13 '10 at 23:02
  • 1
    is it possible to achieve the same behavior without the input element? i.e. can i somehow trigger (in a documented way, as opposite to lepe's answer) form submission and skip validation at the same time? – ivan Apr 13 '12 at 14:55
  • 11
    Note: this doesn't work if you dynamically add the class cancel, ie `$('input[type=submit]').addClass('cancel')`, the class has to be present on page load. – lolesque Jun 13 '12 at 15:40
  • @lolesque you prob need to call the validation method again unless they have changed the way it works note the date on this answer) – redsquare Jun 13 '12 at 16:57
109

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

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

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

lepe
  • 24,677
  • 9
  • 99
  • 108
  • Hello @lepe, you know how to re-apply jquery validation after writing `$("form").validate().cancelSubmit = true;`. I tried `$("form").validate().cancelSubmit = false;` and calling `$("form").validate();` on submit of my submit button. Thanks – Jaikrat Oct 30 '15 at 14:43
  • 3
    It can be done like `$(yourForm).data('validator').cancelSubmit = false;` Thanks – Jaikrat Oct 30 '15 at 14:58
23

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

Daniel Garcia
  • 699
  • 8
  • 15
17

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

Jeffin
  • 1,099
  • 12
  • 23
TastyCode
  • 5,679
  • 4
  • 37
  • 42
10

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.

BrokeMyLegBiking
  • 5,898
  • 14
  • 51
  • 66
3

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

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • that's 4 hours of screwing around for a damn `Pay with PayPal` submit button – Simon_Weaver Jul 01 '13 at 10:11
  • This didn't work for me with the default MVC 5 template. I have Nuget packages JQuery 1.10.2, JQuery Validation 1.11.1, Microsoft jQuery Unobtrusive Validation 3.0.0. What did work for me is replacing the two lines in your code by: `$(this).closest('form').data("validator", null).unbind().submit();` This will set the validator to null and unbind it. After that it will submit the form. You can reset the validation by this line: `$.validator.unobtrusive.parse($("#YourUniqueFormId"));` – LockTar Dec 11 '13 at 08:17
  • somewhere along the line this was fixed. I've been able to completely comment this out and it works now with a `.cancel` class. note: if you're using an type='image' submit button then the `.cancel` class won't work unless you change `":submit"` to `":submit,:image"` in the jquery original validation plugin – Simon_Weaver Apr 25 '14 at 18:51
2
$("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 :)

  • In case you want to just exclude a specific class from being validated, you could use that instead of an asterisk. ```$("form").validate().settings.ignore = "class-name";``` – James Poulose Apr 02 '18 at 18:33
2
<button type="submit" formnovalidate="formnovalidate">submit</button>

also working

user3024034
  • 117
  • 2
  • 4
1

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.

bradlis7
  • 3,375
  • 3
  • 26
  • 34
1

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.

Scott Mayers
  • 437
  • 6
  • 18
1

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();
});
Bugfixer
  • 2,547
  • 2
  • 26
  • 42
0

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();
});
Lucy
  • 73
  • 1
  • 9