Html 5 Form validation without Form

前端 未结 1 628
北荒
北荒 2021-01-20 00:31

Can a html5 form validation

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 01:20

    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) ...
    

    or use the invalid event which is fired when checkValidity() fails:

    email.addEventListener("invalid", function() { alert("Email invalid"); });
    

    You can use setCustomValidity to set the validity status and/or error message:

    if (!email.value) email.setCustomValidity("Email is missing");
    

    0 讨论(0)
提交回复
热议问题