简体   繁体   English

event.preventDefault() 在验证中不起作用

[英]event.preventDefault() not working in validation

I have a page where users can comment under posts.我有一个页面,用户可以在帖子下发表评论。 The post and comments are loaded using ajax.使用 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.使用 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.现在表单正在验证并显示错误消息,但表单正在使用 ajax 提交。 event.preventDefault() is not working. event.preventDefault()不起作用。 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在提交新帖子时,帖子列表会使用 ajax 进行更新,在这种情况下这不起作用

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')..... event.target.className.matches('需要验证').....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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