Bypass HTML "required" attribute when submitting

Horst Walter picture Horst Walter · Sep 10, 2013 · Viewed 30.6k times · Source

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

Answer

Bergi picture Bergi · Sep 10, 2013

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>