How to bind to the submit event when HTML5 validation is used?

后端 未结 3 1350
情话喂你
情话喂你 2020-12-17 20:58

Using HTML5 validation...

In HTML5 browsers, validation occurs before the submit event. So if the form is invalid, the submit event never fires

3条回答
  •  囚心锁ツ
    2020-12-17 21:23

    Yes, there is an event for that reason. The event is called invalid when user tries to submit the for orr when you check validity via HTML5 validation method checkValidity(). This event does not fire on blur or something like that without calling checkValidity() just because you have HTML validation attributes in your input tags. But it does fire on before form submit.

    From W3C:

    When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.

    For example you have this markup:

    Then you need to call checkValidity() to fire invalid event if the input data is invalid:

    document.querySelectorAll('input')[0].addEventListener('blur', function(){
            this.checkValidity();
        }, false);
    
    document.querySelectorAll('input')[0].addEventListener('invalid', function(){
            console.log('invalid fired');
        }, false);
    

    Look at my example here: http://jsbin.com/eluwir/2

提交回复
热议问题