HTML 5表单验证(无表单) [英] Html 5 Form validation without Form
问题描述
可以进行html5表单验证
Can a html5 form validation
<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>
推荐答案
是的,请使用约束验证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_validation 或 https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLSelectElement/checkValidity .例如:
Yes, use the constraint validation API. See http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api. For instance, you can call element . checkValidity()
. See also https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation or https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity. For example:
var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...
或使用invalid
事件,该事件在checkValidity()
失败时触发:
or use the invalid
event which is fired when checkValidity()
fails:
email.addEventListener("invalid", function() { alert("Email invalid"); });
您可以使用setCustomValidity
设置有效性状态和/或错误消息:
You can use setCustomValidity
to set the validity status and/or error message:
if (!email.value) email.setCustomValidity("Email is missing");
这篇关于HTML 5表单验证(无表单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!