1

I was looking through the Constraint Validation API and found some example code online that seemed to call checkValidity() on <form> elements:

(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);
})();

But I tried to do this myself and it didn't work. I couldn't find any reference to this being possible anywhere else either. As far as I figured, it can't be called on <form>. Could someone help me out?

TylerH
  • 20,799
  • 66
  • 75
  • 101
edddd
  • 433
  • 3
  • 17
  • of course you can, I did it a lot ... https://www.w3schools.com/js/js_validation_api.asp – john Smith Sep 14 '20 at 16:16
  • If I understand well, you can use `checkValidity()` on some `input` element but not on `form`... : https://www.w3schools.com/js/js_validation_api.asp ... There is browser support list : https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity – nelek Sep 14 '20 at 16:16
  • @johnSmith that's calling it on `` right? I was asking about ``. But thanks anyways :) – edddd Sep 14 '20 at 16:25
  • @edddd dude just use it on form element it works i dont have a feeling that you tried anything – john Smith Sep 14 '20 at 16:31
  • 1
    it will return true if all of its input-elements' constraints are met. – john Smith Sep 14 '20 at 16:33

2 Answers2

2

You are using submit , but if you are using input there is no submit event for it. You can use input or paste event handler for input

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>
brk
  • 48,835
  • 10
  • 56
  • 78
1

Actually there are many ways to dot this. It seems like you have written a self-invoking JS function. In the other simple way, you can simply write a onsubmit event attribute in tag and write the function name.

e.g.

<form onsubmit="return checkValidity()">
        //...rest stuff
</form>

Based on the returned result from the function, whether true or false depending on the conditions the form will get submitted or stop submission respectively.