Reputation: 335
Here is my javascript code. I am getting contact us page even if validation fail. how to fix this? Can anyone help me.Thanks
(function () {
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) {
form.classList.add('was-validated');
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
window.location.href = "contact.html";
}, false);
});
}, false);
})();
Upvotes: 0
Views: 244
Reputation: 751
From your code, you are checking the result of form validation which is fine. Bu at the end, you are still redirecting the user. You need to add return; in your code after validation is failed or add the redirection in else block
(function () {
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) {
form.classList.add('was-validated');
event.preventDefault();
event.stopPropagation();
return;
}
form.classList.add('was-validated');
window.location.href = "contact.html";
}, false);
});
}, false);
})();
Or:
(function () {
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) {
form.classList.add('was-validated');
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
window.location.href = "contact.html";
}
}, false);
});
}, false);
})();
Upvotes: 1