1

I have set up a basic contact form which emails the form data via PHP. This works fine but I am having trouble intregrating validation script into the code to prevent the form from submitting when no data is entered.

My code so far is:

PHP to Email the data:

<?php  
//validate 
if(isset($_POST['submit']))
{
$to="[email protected]";
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject="Contact Us";
$body="Name: $name \n\n Email Address: $email \n\n";
$sent=mail($to, $subject, $body);
echo 'Sent'; die;  
} 
// 
?>

JS to post the form:

$(document).ready(function() {
$("#form1").validate({
    submitHandler: function() {
        //submit the form
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
            $("#form1").serialize(), 
            function(data){
              //if message is sent
              if (data == 'Sent') {
                $("#message").fadeIn(); //show confirmation message

            }
            //
        });
        return false; //don't let the page refresh on submit.
    }
}); //validate the form
});

HTML Form

<div id="contact-form">
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 

<input type="text" id="name" name="name"/>
<input type="text" id="email" name="email"/>  
<input name="submit" type="submit" title="Submit" class="submit_go" value="Submit"/>

</form>
<div id="message">Thank you for your message</div>
</div>

I have tried integrating the below validation script but this doesn't prevent the form from submitting?

Validation Script

 function leftValue(e, t, n) {
$(this).text(t.parent()[0].style.left)
}
$(document).ready(function() {
required = ["name", "email"];
email = $("#email");
errornotice = $("#error");
emptyerror = "Required Field";
emailerror = "Required Field";
$("#form1").submit(function() {
    for (i = 0; i < required.length; i++) {
        var e = $("#" + required[i]);
        if (e.val() == "" || e.val() == emptyerror) {
            e.addClass("form-error");
            e.val(emptyerror);
            errornotice.fadeIn(750)
        } else {
            e.removeClass("form-error")
        }
    }
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-  Z0-9]{2,4})+$/.test(email.val())) {
        email.addClass("form-error");
        email.val(emailerror)
    }
    if ($(":input").hasClass("form-error")) {
        return false
    } else {
        errornotice.hide();
        return true
    }
});
$(":input").focus(function() {
    if ($(this).hasClass("form-error")) {
        $(this).val("");
        $(this).removeClass("form-error")
    }
})
});

2 Answers 2

1

Aside of your validation in the client you really have to do the validation on the server side all over (in PHP). There is NO guarantee whatsoever that the client side validation happens (users might even have disabled javascript completely), nor that the input comes from your page at all.

Client side validation: eye-candy for the user

Server side validation: where the real security and protection happens.

FWIW: html5 allows for client side validation by the browser.

<form [...]> 
  <input type="text" id="name" name="name" required="required" placeholder="Name" minlength="2" />
  <input type="email" id="email" name="email" required="required" placeholder="Email" />  
  <input name="submit" type="submit" title="Submit" class="submit_go" value="Submit" />
</form>

More info:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, although the Ajax part of my code is still not stopping the normal form from submitting, even when using server side validation?
ajax call: you call the PHP code from the client, the server does the validation, and (optionally) acts on it and returns a code: succes or error and error message. Your calling javascript then needs to react to the returned value and optionally display the error message from the server.
0

It might just be as simple as $(":input").hasClass("form-error") > $("input").hasClass("form-error"). I don't see anything else that would prevent this from working.

Although I'd suggest another route. Instead of adding the class form-error to the inputs, then looking for inputs with that class at the end to determine if there was an error, why not just set a boolean flag saying there was an error. That way, there's no additional DOM lookup, which is an expensive operation.

$("#form1").submit(function() {
    var isValid = true;
    for (i = 0; i < required.length; i++) {
        var e = $("#" + required[i]);
        if (e.val() == "" || e.val() == emptyerror) {
            e.addClass("form-error");
            e.val(emptyerror);
            errornotice.fadeIn(750);
            isValid = false;
        } else {
            e.removeClass("form-error")
        }
    }
    if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-  Z0-9]{2,4})+$/.test(email.val())) {
        email.addClass("form-error");
        email.val(emailerror);
    }
    if (!isValid) {
        return false;
    } else {
        errornotice.hide();
        return true;
    }
});

3 Comments

Thanks for the tip. That has solved the problem with the validation but now when the form is submitted it displays a new page with the words 'Sent' rather than displaying the #message div on the same page as the form?
I think what's happening is the ajax call goes, but your form is still submitted normally as well. You need to return false from the function with your ajax request.
This stops the validation from working - Could it be related to the $("#form1").validate({ function as I was originally using the default jquery validation script to set up the form but changed to the other validation script above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.