Bypass HTML “required” attribute when submitting [duplicate]

拜拜、爱过 提交于 2019-11-30 06:02:51

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!