没有表单的Html 5表单验证

标签 html validation

能否实现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_validationhttps://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/

相关文章:

html - 自定义嵌套选项卡 (HTML/CSS)

c - 如何编写一个 C 程序来确定输入是否为质数和数字

html - html验证器中的"Stray start tag footer"?

PHP验证灵活有效的URI

javascript - 循环遍历数组以查找用户输入的索引,然后替换另一个数组的相同索引处的值

javascript - HTML5 localMediaStream 停止功能不释放网络摄像头/硬件

forms - 如何使用 Play 正确验证表单!在斯卡拉?

php - 一些关于 RSS 提要的帮助

jquery - 具有固定标题/列的 HTML 表格 - css 解决方案 - 在 Firefox 中不起作用

asp.net - 构建时验证所有 ASPX、ASCX 和 HTML 文件