简体   繁体   中英

How to properly redirect page after form validation in JavaScript?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM