0

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). And mail.php (update: 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).

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). 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). Any help would be greatly appreciated!:)

UPDATE: form html: (removed as unnecessary now)

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:

$('#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.

dmtrrrr
  • 65
  • 1
  • 6

3 Answers3

0

You want to prevent the default action of the button and then call submit when you are ready.

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');
            }
        }); 
    });
tlays
  • 371
  • 2
  • 8
  • thank you for your answer! I'm sorry, I'll try to clarify it further: there were "error" & "error_show" classes in demo CSS and "span" under input fields in HTML. I removed them. But they are still in this script (3 lines/rows down starting from var error_element=$("span") and (probably) are causing the problem. :| – dmtrrrr Jun 01 '18 at 15:16
  • I inserted your code in place of mine and now when I click "SEND" button, it shows "No errors. Form will be submitted" when everything is valid and when something is invalid and sends nothing in both cases... :| – dmtrrrr Jun 01 '18 at 15:33
0

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;

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

        }); 
    });
ssten
  • 1,276
  • 1
  • 11
  • 24
  • thank you for your readiness to help! :) the method is POST... :| – dmtrrrr Jun 01 '18 at 15:47
  • Then the AJAX call method needs to be POST as well, I edited my answer! – ssten Jun 01 '18 at 15:52
  • I have inserted your modified code and it sends everything without any alerts (good), despite highlighted invalid fields. So, those lines (I singled out them in my post update) were not the problem... – dmtrrrr Jun 01 '18 at 16:20
  • The fields are highlighted when you enter some text in it, after the submit that goes away... i edited my answer to do that, what do you want it to do after the submit or if the fields are not filled in? – ssten Jun 01 '18 at 19:45
  • I would like the button do nothing if something is highlighed as invalid, and send everyhting if everything is valid.... I don't understand what's wrong with my form, why real-time validation works and validation on submit doesn't... Thank you for your time and willingness to help! :) – dmtrrrr Jun 01 '18 at 20:21
  • When you click on #button, it checks if the inputs have the class "valid", if not, they get the class "invalid" and the AJAX is not triggered – ssten Jun 02 '18 at 06:21
0

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:

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:

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. If it detects there is an invalid control, it exits the loop and does not proceed with Posting the form.

Hope that helps.

Ryan Gibbs
  • 1,178
  • 10
  • 24
  • Thank you! I'll try both solutions right now to see what happens. Then, I'll comment again here.;) – dmtrrrr Jun 01 '18 at 17:37
  • nothing works, I'have probably broken something.:| I have a strange idea, since "valid" and "invalid" classes are added properly by the 3 first paragraphs of validation: could you please help me remove the last paragraph of that validation with IF ELSE combo i.e.: if "#contact_name" has class "valid", "#contact_email" has class "valid", "#contact_message has class "valid", then button simply POSTs my form, if not - nothing happens? My form drives me mad.:) – dmtrrrr Jun 01 '18 at 19:11
  • That's what solution 2 does. It checks all your inputs in your form for that class. Are you getting any console errors? – Ryan Gibbs Jun 01 '18 at 19:15
  • my last 2 ideas (that may be not very good): input fields are wrapped in div ids for CSS styling and maybe "valid" and "invalid" are added to input fields' "parents", that's why validation on submit in the last paragraph "doesn't see" them?... Another one: there are 4 checkboxes (also input, not required, not validated), maybe they break the whole validation on submit? – dmtrrrr Jun 01 '18 at 23:09
  • I can't really understand what you mean. Is it possible to update your question with your html and also check your developer console for any errors? – Ryan Gibbs Jun 01 '18 at 23:24
  • Hello again! Thank you for your patience and time:) I've added form's html to the post. I have no idea where developer's console is located :o :D I use WAMP/sendmail to test it. – dmtrrrr Jun 02 '18 at 00:16