0

I have a submit button on my MVC form (with unobtrusive validation enabled) which has the cancel class:

<input type="submit" name="Go back" value="1" class="cancel" />

The cancel class allows the form to POST even if input fields have validation errors. But the validation error messages are nonetheless displayed as soon as the button is clicked, and remain visible until the server completes the round trip and the page is redisplayed.

Is there something baked into MVC that I'm missing, or do I need to write my own JS code to find and hide all validation messages if the submit element has the "cancel" class?

Bob.at.Indigo.Health
  • 11,023
  • 13
  • 64
  • 111
  • 1
    There is no reason to make your cancel into a submit button. The submit is causing your whole form to be submitted and if you have validation on it then it will fail everytime. Remove the submit and then simply use an input of type button with cancel. On click call the action you want in your controller. – Gjohn Dec 05 '14 at 20:02
  • Ok, so I edited the example to clarify that the button is not necessarily performing a "cancel" function (whatever that may mean). There are many reasons why one might have a button that performs a POST operation without validating the inputs. For example, I may have a "back" button that returns to a previous page in a multi-page wizard or interview. Or I may be asking the user for a validation code that I sent by email, and I need a button to the user can click to re-send the validation email... – Bob.at.Indigo.Health Dec 06 '14 at 18:07
  • ... True, submit buttons for functions that don't want to validate inputs can be contained in their own `
    ` blocks, but that complicates the page layout.
    – Bob.at.Indigo.Health Dec 06 '14 at 18:09

1 Answers1

0

Disable client-side validation in MVC 3 "cancel" submit button

People seems to have the popup validation problem to and someone is saying in the comment that's it's not working in MVC4 and MVC5.

Personnaly, il will greatly suggest you to control this behavior by yourself on the form submit event and use ajax to post the form.

$("MyForm").submit(function( event ) {
    event.preventDefault(); //prevent the default submit
    if (!$(this).find("input[type=submit]").hasClass("cancel"))
    {
        if (!$("form").validate())
        {
            return false;
        }
    }
    $.ajax({
       type: "POST",
       url: url,
       data: $("MyForm").serialize(), // serializes the form's elements.
       success: function(data)
       {
           //do something
       }
     });

});

I'm not sure this will prevent the validation from poping on the submit button click.

An other solution would be to change the submit button to a normal button and control the validation and the submit of the form on your own.

Community
  • 1
  • 1
Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10