简体   繁体   中英

Validating Contact Form with Captcha

I have a contact form with a captha in it. There is no problem submitting mail, but the issue I have is validation and transferring the values to submit handler. I have limited knowledge of PHP and Javascript. I humbly seek your help in checking these codes and tell me what I need to do to get it right. Any help will be appreciated!

Below are the mail handler php codes

<?php

require_once('recaptchalib.php');
$publickey = "***********"; 
$subject = 'CONTACT MESSAGE: '  ; //. $_REQUEST['subject']Subject of your email
$to = 'myemailaddress@domain.com';  //Recipient's E-mail
$privatekey = "***********";
$resp = recaptcha_check_answer ($privatekey,
                            $_SERVER["REMOTE_ADDR"],
                            $_POST["recaptcha_challenge_field"],
                            $_POST["recaptcha_response_field"]);

if ($resp->is_valid) {


$headers  = 'MIME-Version: 1.0' . "\r\n";



$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";



$message .= 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Telephone: ' . $_REQUEST['telephone'] . "<br>";
$message .= 'Email: ' . $_REQUEST['email'] . "<br>";
$message .= 'Message: ' . $_REQUEST['message'];

if (@mail($to, $subject, $message, $headers))

{

    // Transfer the value 'sent' to ajax function for showing success message.

    echo 'sent';
}

else
{

    // Transfer the value 'failed' to ajax function for showing error message.
    echo 'failed';

}

 } else {

    echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error;
}

?>

And here is the javascript

<script>

function validateForm() {
    var x = document.forms["enquiries"]["name"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your full name", "error");
        return false;
    }

     var x = document.forms["enquiries"]["email"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your a valid email address", "error");
        return false;
    }

     var x = document.forms["enquiries"]["message"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
        return false;
    }


    // If there is no validation error, next to process the mail function
            if(error == false){

                /* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
                $.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
                    //Check the result set from email.php file.
                    if(result == 'sent'){
                        sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
                    }else{
                        //Display the error message

                    }
                });
            }

}

</script>

and finally, the html

    <form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">  

<label>  <input name="name" type="text" id="name" style="width: 90%;" placeholder="Name" ></label>

<label><input name="email" type="text" id="email" style="width: 90%;" placeholder="Email"></label>

<label><textarea name="message" id="message" style="width: 96.5%;" class="mssg" rows="10" placeholder="Message"></textarea>
</label>

<label><?php echo recaptcha_get_html($publickey) ?></label>

<label><input name="submit" type='submit' id='mssg_buttton' value='Send Message'></label>

</form>
  1. When I clicked on the submit button, I was taken straight to processContactEmail.php page without the form validating
  2. How do I display this error: echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->error; in my alert
  3. I'm not sure about this line if(error == false){ in the JS script since there is no variable declared

The first problem looks like your validation function is referred to in your HTML as validate();

<form name="enquiries" id='enquiries' method="post" action='processContactEmail.php' onSubmit="return validate();">

But in your Javascript the function defined is called validateForm() . To fix that just make sure these are called the same thing (doesn't matter what, as long as they match).

Rather than calling the validation function inline with onSubmit="return validate();" , it's better to attach a separate event listener in the Javascript. It's good practice to separate your HTML and Javascript code. I see you're using JQuery, so you do this in your Javascript like so:

$( document ).ready(function() { // Make sure DOM is loaded before attaching the event listener to the form element
    $("#enquiries").on("submit", validateForm); // Add submit listener to the form with the id 'enquiries'  and run the function called validateForm on submit
});

Secondly, in your validate function, you need to prevent the form's default action of submitting and redirecting to the action processContactEmail.php. The HTML form will always try to post to its default action, so do make it do something else (like validate) you must actively stop it from posting.

You do this in JQuery by editing your validateForm function to prevent the form's default action with event.preventDefault. As for the error, you must first set an error variable to false (assume all is fine) and as you find errors, you change it to true. If it's still false after the checks, there were no errors.

Your Javascript function should look like this:

function validateForm(event) {

    event.preventDefault(); // the variable "event" is automatically included in the submit event listener.

    var error = false; // Assume it's fine unless proven otherwise

    var x = document.forms["enquiries"]["name"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your full name", "error");
        error = true; // The form is not fine. Set error to true.
        // No return, or you will not get to the rest of your function
    }

    var x = document.forms["enquiries"]["email"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your a valid email address", "error");
        error = true; // The form is not fine. Set error to true.
    }

    var x = document.forms["enquiries"]["message"].value;
    if (x == null || x == "") {
        sweetAlert("Oops...", "Please enter your the message you wish to send", "error");
        error = true; // The form is not fine. Set error to true.
    }


    // If there is no validation error, next to process the mail function
    if(error == false){  // error was never set to true, so it must still be false and the form is OK.

        /* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php */
        $.post("processContactEmail.php", $("#enquiries").serialize(),function(result){
            //Check the result set from email.php file.
            if(result == 'sent'){
                sweetAlert("Congratulations", "Your message has been sent successfully!", "success");
            } else {
                //Display the error message

            }
        });
    }
}

After these changes, your form will not post to its action, and your validateForm function should run, check for the errors, and if there are none, make the ajax POST to processContactEmail.php.

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