a way to check validity of HTML5 forms?

后端 未结 3 786
小鲜肉
小鲜肉 2020-12-04 17:29

Is it possible to check if an input element of an html5 form is valid based on the pattern I set for it? I know the psuedo class stuff.. but i\'m hoping something like:

相关标签:
3条回答
  • 2020-12-04 18:12

    there are two ways to check the validity.

    1. inputElement.checkValidity() returns true or false
    2. inputElement.validity returns the validity-state object. inputElement.validity.valid returns true/false

    Instead of using keyup, you can also use the 'input' event. All browser, which have implemented the constraint validation API, have also implemented the input-event.

    If you are using option 1 above, Opera has a bug here and will show its validation hint. So you should use 2.

    I have created a html5 forms library, which implements all unknown features to incapable browsers + fixes issues in HTML5 browsers. So everything works like defined in the spec, but it's built on top of jQuery. (http://afarkas.github.com/webshim/demos/index.html).

    0 讨论(0)
  • 2020-12-04 18:24

    You can use the pattern attribute.

    It will validate it client side, so no need to validate it again client side.

    Example

    jsFiddle.

    But, make sure you do it again server side.

    Also note, because browser compatibility is quite poor right now, JavaScript is the norm for validating client side.

    0 讨论(0)
  • 2020-12-04 18:24

    To complement, you can check each element was invalid and, for example, set a focus in the first invalid element, by this code:

    var Form = document.getElementById('FormID');
    if (Form.checkValidity() == false) {
        var list = Form.querySelectorAll(':invalid');
        for (var item of list) {
            item.focus();
        }
    }
    
    0 讨论(0)
提交回复
热议问题