能否实现html5表单验证
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
可以不用Form吗
<div>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</div>
最佳答案
是的,使用约束验证 API。参见 http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api .例如,您可以调用 element 。检查有效性()
。另见 https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation或 https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity .例如:
var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...
或者使用在 checkValidity()
失败时触发的 invalid
事件:
email.addEventListener("invalid", function() { alert("Email invalid"); });
您可以使用setCustomValidity
来设置有效性状态和/或错误消息:
if (!email.value) email.setCustomValidity("Email is missing");
关于没有表单的Html 5表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758303/