可以进行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>
答案 0 :(得分:4)
是的,使用约束验证API。见2。例如,您可以致电element . checkValidity()
。另请参阅http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api或https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation。例如:
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");