当您通过 HTML 对表单元素应用 HTML 验证并且该元素的值不符合验证条件时,将不会提交表单。
但是,如果涉及到 JavaScript,则必须控制此过程。最简单的方法是简单地检查表单的有效性。
“但是,当使用 JavaScript 提交表单时,我是否必须重新验证每个字段?”
正如您将在我的 sn-p 中看到的,您必须验证表单,这可以通过一个简单的方法调用来完成。如果需要,您可以检查每个元素以查看哪些无效以及原因并采取相应措施。
"也就是说,HTML5验证只是一个视觉工件,它不会阻止表单提交。如果用户想输入错误的内容,而忽略红旗,他可以做到。 "
当您只使用 HTML 而不使用 JavaScript 时,验证就不仅仅是视觉上的了。表格将不会提交。该功能已融入兼容 HTML5 表单的浏览器中。
“如果我的判断是正确的,我为什么要使用 HTML 来做一些我可以(而且我必须)用 JS 做的事情?也许 JS 有办法知道一切正常继续,无需执行任何进一步检查。”
同样,仅使用 HTML 标记将为您提供各种验证器(必需、模式、数字等),并且它们可以直接使用。但是,您将无法控制验证消息的内容或显示它们的确切时间和位置(甚至它们的外观)。这完全取决于浏览器。这就是为什么 HTML5 表单规范包含一个非常强大的 API(通过 JavaScript)对应物 - 让您可以完全控制验证和通知过程。
var btn = document.getElementById("btnSubmit");
var frm = document.getElementById("frmTest");
btn.addEventListener("click", function(){
// The HTML 5 Forms API provides a .checkValidity()
// method to your form object so that you can know
// if the form is valid or not:
if(frm.checkValidity()){
frmTest.submit();
}
});
<form method=post action="http://www.somewhere.com" id=frmTest>
<input required>
<input type=button id=btnSubmit value=submit>
</form>
这是一个基本的 JavaScript 函数,它演示了使用 HTML5 表单 API 可以完成的工作:
// Custom form validation logic:
function validate(evt) {
// An HTML5 form has a checkValidity() method which forces it
// to examine the validity of all controls that know how to validate
// and it returns a boolean indicating if ALL these controls are valid
// or if any ONE of them is not.
var valid = theForm.checkValidity();
if (valid) {
// Everything is good. Submit the form:
theForm.submit();
} else {
// At least one form element is invalid. Loop through all the elements to
// see which one(s) they are:
var theElements = theForm.elements;
for (var i = 0; i < theElements.length; i++) {
var theElement = theElements[i];
// If the form element participates in the HTML5 Validity Framework and
// if it is invalid...
if (theElement.willValidate && !theElement.validity.valid) {
console.warn(theElement.id + " validity details: ");
// ...The object will have a validity object property:
console.log(theElement.validity);
// The element is invalid. Loop through all the validity object's
// properties to see why it is invalid:
for (var constraint in theElement.validity) {
// Check the particular validity constraint for true
if (theElement.validity[constraint]) {
// Update the span element next to the offending form element with the reason:
theElement.nextElementSibling.innerHTML = constraint;
} // End If
} // End For
} // End If
} // End For
} // End If
} // End Function