Reputation: 482
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?
Upvotes: 2
Views: 2494
Reputation: 13
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.
Upvotes: 0
Reputation: 50346
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>
Upvotes: 2