Bypass HTML “required” attribute when submitting [duplicate]


I use required for a 1st check before submitting a form.

<form action="myform.php">
  Foo: <input type="text" name="someField" required="required">
  <input type="submit" value="submit">
  <input type="submit" value="ignore">
</form>

Problem is, that I have an "ignore" button, which submits the form as well and the backend logic then sets a correct state in a DB. In this case (ignore) the validation is not desired (because there is no need to fill in field "Foo").

What's the best way to handle the 2 scenarios?

  1. I am aware that I could give up "required" and do the validation somewhere else (backend / JavaScript). I am looking for a way to keep the "required".
  2. I could use some Js onclick for the ignore button scenario and remove the attribute just before sending the form ( https://stackoverflow.com/a/13951500/356726 ).

But actually I am looking for something smarter ....

--- Edit ---

Yes, duplicate of Required attribute HTML5

No JavaScript, no second form needed, and the validation can stay:

For exactly this use case the HTML5 spec has designed the formnovalidate attribute for submit elements (like <input type=submit>), as one of the attributes for form submission:

The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.

So simply put

<form action="myform.php">
  Foo: <input type="text" name="someField" required>
  <input type="submit" value="submit">
  <input type="submit" value="ignore" formnovalidate>
</form>

Your #2 is a common approach. Something like:

$('input[value="ignore"]').click(function() {
    $(this).siblings('input[type="text"]').removeAttr('required');
});

Might have to use mousedown to beat submit.


If you don't want to use Javascript, you could make them separate forms and have all the inputs set to hidden for the ignore form.

Not the best option, but it is an alternative.


You should use approach #1 on the following grounds: The main reasons for using required instead of JavaScript validation is that it is simpler and it works even when JavaScript is disabled. Here the simplicity does not apply, since the use of required makes things more difficult. And the latter reason does not apply either: with JavaScript disabled and the browser supporting required, the “ignore” button does not work unless some data is entered in the textfield.

Another alternative is the one mentioned on @MattKenefick’s answer. It might even result in simpler structure and logic. If the form is really as simple as in the example, it is straightforward to split it to two forms:

<form action="myform.php">
  Foo: <input type="text" name="someField" required="required">
  <input type="submit" value="submit">
</form>
<form action="myform.php">
  <input type="submit" value="ignore">
</form>