HTML5表单验证无需表单

5

HTML5表单验证是否可行?

<form>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</form>

可以不使用表单来实现吗?

<div>
    <input type="email" id="email" placeholder="Enter your email here..." required>
    <button type="submit">Submit</button>
</div>
2个回答

5
是的,可以使用约束验证API。请参见http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api。例如,您可以调用element.checkValidity()。另请参见https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validationhttps://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity。例如:
var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...

或者使用invalid事件,该事件在checkValidity()失败时触发:

email.addEventListener("invalid", function() { alert("Email invalid"); });

你可以使用setCustomValidity来设置有效性状态和/或错误消息:
if (!email.value) email.setCustomValidity("Email is missing");

1
如果您想查看页面中的错误,而不仅仅是收到验证结果的布尔值,则可以使用以下内容:
document.gelElementById('email').reportValidity();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接