输入类型不是“提交"时的 HTML5 验证
我使用 HTML5 来验证字段.我在单击按钮时使用 JavaScript 提交表单.但是 HTML5 验证不起作用.仅当输入类型为 submit
.除了使用 JavaScript 验证或将类型更改为 submit
之外,我们还能做些什么吗?
I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit
. Can we do anything other than using JavaScript validation or changing the type to submit
?
这是 HTML 代码:
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
我正在函数 submitform()
中提交表单.
I'm submitting the form in the function submitform()
.
HTML5 表单验证过程仅限于通过提交按钮提交表单的情况.表单提交算法明确表示不执行验证当表单通过 submit()
方法提交时.显然,这个想法是,如果您通过 JavaScript 提交表单,则应该进行验证.
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit()
method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
但是,您可以使用 checkValidity()
方法根据 HTML5 属性定义的约束请求(静态)表单验证.如果您想显示与浏览器在 HTML5 表单验证中所做的相同的错误消息,恐怕您需要检查所有受约束的字段,因为 validityMessage
属性是字段的属性(控制),而不是形式.在单个受约束字段的情况下,如所呈现的情况,这当然是微不足道的:
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity()
method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage
property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}