HTML5 validation when the input type is not “submit”

后端 未结 9 1350
醉酒成梦
醉酒成梦 2020-11-29 01:42

I\'m using HTML5 for validating fields. I\'m submitting the form using JavaScript on a button click. But the HTML5 validation doesn\'t work. It works only when then input ty

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 01:59

    2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.

    The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.

    Updated solution snippet:

    function submitform() {
      var f = document.getElementsByTagName('form')[0];
      if(f.reportValidity()) {
        f.submit();
      }
    }
    

提交回复
热议问题