【问题标题】:Html 5 Form validation without Form没有表单的 HTML 5 表单验证
【发布时间】:2015-08-01 04:40:29
【问题描述】:

可以一个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>

【问题讨论】:

    标签: html validation


    【解决方案1】:

    是的,使用约束验证 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_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");
    

    【讨论】:

      【解决方案2】:

      如果您想查看页面中的错误,而不仅仅是接收带有验证结果的布尔值,您可以使用:

      document.gelElementById('email').reportValidity();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 2014-12-08
        • 1970-01-01
        • 2014-08-10
        • 2019-02-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多