没有表单的Html 5表单验证

时间:2015-08-01 04:40:30

标签: html5 validation

可以进行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>

1 个答案:

答案 0 :(得分:4)

是的,使用约束验证API。见2。例如,您可以致电element . checkValidity()。另请参阅http://www.w3.org/TR/html5/forms.html#the-constraint-validation-apihttps://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");