HTML 5表单验证(无表单) [英] Html 5 Form validation without Form

查看:105
本文介绍了HTML 5表单验证(无表单)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆