简体   繁体   中英

event.preventDefault() not working in validation

I have a page where users can comment under posts. The post and comments are loaded using ajax. I am trying to validate the comment form using the below code.

document.querySelector('body').addEventListener('submit', event => {
                if (event.target.matches('.needs-validation')) {
                    if (event.target.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        event.target.classList.add('was-validated');
                }
            }, false);

The comment form is submitted using ajax.

$('body').on('submit', '.cmnt-frm', function(e) {

Now the form is getting validated and an error message is showing, but the form is getting submitted using ajax. event.preventDefault() is not working. The below code works, but only for the initial page load. On submitting a new post the post list gets updated using ajax, in that case this doesn't work

window.addEventListener('load', function() {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');
                // Loop over them and prevent submission
                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);

What is wrong with the code. Please help.

event.target.className.matches('needs-validation').....

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