绕过HTML“必需”提交时的属性 [英] Bypass HTML "required" attribute when submitting
问题描述
在提交表单之前,我使用必需
进行第一次检查。
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>
问题是,我有一个忽略按钮,它同时提交表单和后端逻辑然后在DB中设置正确的状态。在这种情况下(忽略)不需要验证(因为不需要填写字段Foo)。
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").
处理2个场景的最佳方法是什么?
What's the best way to handle the 2 scenarios?
- 我知道我可以放弃必需并在其他地方进行验证(后端/ JavaScript)。我正在寻找一种方法来保持必需。
- 我可以使用一些Js
onclick
作为忽略按钮场景并删除发送表单之前的属性( https://stackoverflow.com/a/13951500/356726 )。
- 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".
- 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 ....
---编辑---
是的,重复必需属性HTML5
推荐答案
没有JavaScript,不需要第二种形式,验证可以保留:
No JavaScript, no second form needed, and the validation can stay:
对于这个用例,HTML5规范设计了 <提交元素的code> formnovalidate 属性(例如 < input type = submit& gt;
),作为表单提交的属性:
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:
formnovalidate
属性可以是用于制作不触发约束验证的提交按钮。
The
formnovalidate
attribute can be used to make submit buttons that do not trigger the constraint validation.
所以简单地把
<form action="myform.php">
Foo: <input type="text" name="someField" required>
<input type="submit" value="submit">
<input type="submit" value="ignore" formnovalidate>
</form>
这篇关于绕过HTML“必需”提交时的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!