简体   繁体   English

jQuery表单:关于提交验证问题+提交后留在同一页面上

[英]jQuery form: on submit validation issue + stay on the same page after submit

I'm not a programmer, just trying to fix & improve my contact form. 我不是程序员,只是试图修复和改进我的联系表。 Right now it's a HTML form (name, email, 4 checkboxes as subject, message). 现在,它是一个HTML表单(名称,电子邮件,4个复选框作为主题,消息)。 And mail.php (update: method="POST"). 和mail.php(更新:method =“ POST”)。 Everything works, I receive all form data. 一切正常,我收到所有表格数据。

But I have found a script to validate name, email & message inputs, here it is: 但是我发现了一个脚本来验证名称,电子邮件和消息输入,这里是:

<script>
        $(document).ready(function() {
            <!-- Real-time Validation -->
            <!--Name can't be blank-->
            $('#contact_name').on('input', function() {
                var input=$(this);
                var is_name=input.val();
                if(is_name){input.removeClass("invalid").addClass("valid");}
                else{input.removeClass("valid").addClass("invalid");}
            });

            <!--Email must be an email -->
            $('#contact_email').on('input', function() {
                var input=$(this);
                var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
                var is_email=re.test(input.val());
                if(is_email){input.removeClass("invalid").addClass("valid");}
                else{input.removeClass("valid").addClass("invalid");}
            });

            <!--Message can't be blank -->
            $('#contact_message').keyup(function(event) {
                var input=$(this);
                var message=$(this).val();
                console.log(message);
                if(message){input.removeClass("invalid").addClass("valid");}
                else{input.removeClass("valid").addClass("invalid");}   
            });

            <!-- After Form Submitted Validation-->
            $("#button").click(function(event){
                var form_data=$(".myform").serializeArray();
                var error_free=true;
                for (var input in form_data){
                    var element=$("#contact_"+form_data[input]['name']);
                    var valid=element.hasClass("valid");
                    var error_element=$("span", element.parent());
                    if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
                    else{error_element.removeClass("error_show").addClass("error");}
                }
                if (!error_free){
                    event.preventDefault(); 
                }
                else{
                    alert('No errors: Form will be submitted');
                }
            }); 
        });
</script>

Originally, it was showing error messages next to input fields, I decided not to use them (spans in HTML, "error" & "errow_show" classes in CSS), leaving just input field highlighting ("valid" green/"invalid" red CSS classes). 最初,它是在输入字段旁边显示错误消息,所以我决定不使用它们(HTML中的跨度,CSS中的“错误”和“ errow_show”类),仅将输入字段突出显示(“有效”为绿色/“无效”为红色) CSS类)。

I feel like the problem is these lines: 我觉得问题是这些行:

var error_element=$("span", element.parent());
if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
else{error_element.removeClass("error_show").addClass("error");}

And this script highlights empty name, invalid email and empty message. 并且此脚本突出显示了空名称,无效的电子邮件和空消息。 But when I click "SEND" button, the script, despite highlighting invalid fields, shows the alert "No errors. Form will be sumbitted" and sends form to me. 但是,当我单击“发送”按钮时,该脚本尽管突出显示了无效字段,但仍显示警报“没有错误。表格将被加总”并将表格发送给我。 The problem seems to be in its last part. 问题似乎在最后一部分。 I do not know how to properly remove "span", "error" and "error_show" from this script (3 lines before the second IF). 我不知道如何从该脚本中正确删除“ span”,“ error”和“ error_show”(第二个IF之前的3行)。 I want my form to send everything to me if everything is valid and not send anything ("disabled button"?) if something is invalid. 我希望表单在所有内容都有效的情况下将所有内容发送给我,而在某些内容无效的情况下不发送任何内容(“禁用按钮”?)。 Without any alerts. 没有任何警报。 If it also could stay on the same page after sumbitting... it would be an ideal thing ( Submit form and stay on same page? , Submit a form using jQuery , jQuery AJAX submit form ). 如果求和后还可以留在同一页上……那将是理想的选择( 提交表单并留在同一页上?使用jQuery提交表单,使用 jQuery AJAX提交表单 )。 Any help would be greatly appreciated!:) 任何帮助将不胜感激!:)

UPDATE : form html: (removed as unnecessary now) 更新 :表单html:(现在已删除为不必要的内容)

UPDATE 2 : well, guys, this (weird? incorrect? semi-correct?) code I suddenly made up checks and highlights correctly as "valid"/"invalid" all 3 required fields (name, email, message) and shows correct alerts (I'll remove them later) on #button_send click and even sends the whole form with non-required non-validated checkboxes to me: 更新2 :好的,伙计们,这个(奇怪的?不正确的?半正确的?)代码突然组成了检查,并正确地将所有3个必填字段(名称,电子邮件,消息)突出显示为“有效” /“无效”,并显示正确的警报(我将在以后删除它们)在#button_send单击上,甚至将带有不需要的未经验证的复选框的整个表单发送给我:

$('#button_send').click(function(){
if ($('#contact_name').hasClass('valid') && $('#contact_email').hasClass('valid') && $('#contact_message').hasClass('valid')) {
                    alert('No errors');
                    $('.form').submit();
                } else {
                    alert('Errors');
                    return false;
                }
            });

I want to thank everyone for every piece of advice and help . 我要感谢每个人的建议和帮助

You want to prevent the default action of the button and then call submit when you are ready. 您要阻止按钮的默认操作,然后在准备好后调用Submit。

http://api.jquery.com/event.preventDefault/ http://api.jquery.com/event.preventDefault/

        <!-- After Form Submitted Validation-->
        $("#button").click(function(event){
            // prevent the form from being submitted
            event.preventDefault();

            var form_data=$(".myform").serializeArray();
            var error_free=true;
            for (var input in form_data){
                var element=$("#contact_"+form_data[input]['name']);
                var valid=element.hasClass("valid");
                var error_element=$("span", element.parent());
                if (!valid){error_element.removeClass("error").addClass("error_show"); error_free=false;}
                else{error_element.removeClass("error_show").addClass("error");}
            }
            if (error_free) {
                alert('No errors: Form will be submitted');
                // submit the form if no errors
                $( ".myform" ).submit(); 
            }
            else{
                alert('Errors shown');
            }
        }); 
    });

If you want it to be save, I recommend you to do backend validation to. 如果要保存它,建议您进行后端验证。

If in your HTML form, the method is set to "post", this will do the magic; 如果在您的HTML表单中,该方法设置为“ post”,则将发挥作用;

    $(document).ready(function() {
        <!-- Real-time Validation -->
        <!--Name cant be blank-->
        $("#contact_name").on('input', function() {
            var input=$(this);
            var is_name=input.val();
            if(is_name){input.removeClass("invalid").addClass("valid");}
            else{input.removeClass("valid").addClass("invalid");}
        });

        <!--Email must be an email -->
        $("#contact_email").on('input', function() {
            var input=$(this);
            var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
            var is_email=re.test(input.val());
            if(is_email){input.removeClass("invalid").addClass("valid");}
            else{input.removeClass("valid").addClass("invalid");}
        });

        <!--Message cant be blank -->
        $("#contact_message").keyup(function(event) {
            var input=$(this);
            var message=$(this).val();
            console.log(message);
            if(message){input.removeClass("invalid").addClass("valid");}
            else{input.removeClass("valid").addClass("invalid");}   
        });

        <!-- After Form Submitted Validation-->
        $("#button").click(function(event){
            event.preventDefault();
            var form_data=$(".myform").serializeArray();
            var error_free=true;
            for (var input in form_data){
                var element = $("#contact_"+form_data[input]['name']);
                var valid = element.hasClass("valid");
                if (!valid){
                    error_free=false;
                    element.addClass("invalid");
                }                  
            }
            if (error_free){
                //Submit the  form
                $.post({url: 'mail.php', data: form_data, dataType: 'json'}).done(function(){
                    //clear the fields
                    $("[id^=contact_]").val('');
                })
            }

        }); 
    });

The Problem: 问题:

The behavior you're seeing is because you deleted the controls that your code was using to validate/invalidate your form. 您看到的行为是因为您删除了代码用来验证/使表单无效的控件。 Without those controls, due to the way it was written, it defaults to a valid state regardless of the actual validity of the inputs. 如果没有这些控件,则由于其编写方式,无论输入的实际有效性如何,它都默认为有效状态。

Solution #1: 解决方案1:

If you have a backup, the easy thing to do would be to revert back to how it was before you touched it and just add 'hidden' as properties to your spans. 如果您有备份,那么要做的一件简单的事情就是恢复到触摸之前的状态,然后将“隐藏”作为属性添加到跨度中。 This way they wouldn't be visible to your user, but would still validate the inputs for you. 这样,它们对您的用户将不可见,但仍会为您验证输入。

Solution #2: 解决方案2:

If you aren't able to do that, then you'll need to modify your submission code to validate off the remaining controls and their classes. 如果您无法执行此操作,则需要修改提交代码以验证其余控件及其类。 I don't have your full code to test this, but I believe something like this would work: 我没有完整的代码来测试这一点,但是我相信类似的东西会起作用:

<!-- After Form Submitted Validation-->
$("#button").click(function(event){
    var error_free=false;
    $.each($('.myform > input'), function() {
        error_free = $(this).hasClass('valid');
        if (!error_free){
            event.preventDefault();
            return false;
        }
    });
    if (error_free){
      alert('No errors: Form will be submitted');
    }               
});

The snippet above loops over any inputs inside of the control with the class 'myform' and checks if they have the 'valid' class, then sets a variable true or false depending. 上面的代码片段循环使用类“ myform”对控件内部的所有输入进行循环,并检查它们是否具有“ valid”类,然后根据变量设置true或false。 If it detects there is an invalid control, it exits the loop and does not proceed with Posting the form. 如果它检测到存在无效的控件,则退出循环并且不继续发布表单。

Hope that helps. 希望能有所帮助。

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

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