您可以在<form>元素上调用checkValidity()吗?

时间:2020-09-14 16:13:04

标签: javascript html constraint-validation

我正在查看约束验证API,并在网上找到了一些示例代码,这些代码似乎在checkValidity()元素上调用了<form>

(function() {
'use strict';
window.addEventListener('load', function() {
  var forms = document.getElementsByClassName('needs-validation');
  var validation = Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

但是我试图自己做,但是没有用。我在其他任何地方都找不到对此的任何参考。据我了解,它无法在<form>上调用。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您正在使用submit,但是如果您正在使用input,则不会有submit事件。您可以使用inputpaste事件处理程序进行输入

window.addEventListener('load', function() {
  var forms = document.getElementsByClassName('needs-validation');
  var validation = Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('input', function(event) {
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
      form.classList.add('was-validated');
    }, false);
  });
}, false);
<form>
  <input type='email' class='needs-validation'>
  <button type='submit'>Submit</button>
</form>