简体   繁体   English

使用验证码验证联系表

[英]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. 我对PHP和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代码

<?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 这是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 最后是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 当我单击“提交”按钮时,我直接进入processContactEmail.php页面,而无需进行表单验证
  2. How do I display this error: echo "The reCAPTCHA wasn't entered correctly. Go back and try it again.".$resp->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 我不确定JS脚本中的if(error == false){这一行if(error == false){因为没有声明任何变量

The first problem looks like your validation function is referred to in your HTML as validate(); 第一个问题似乎是您的验证函数在HTML中被称为validate();

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

But in your Javascript the function defined is called validateForm() . 但是在您的Javascript中,定义的函数称为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();" 而不是通过onSubmit="return validate();"内联调用验证函数onSubmit="return validate();" , it's better to attach a separate event listener in the Javascript. ,最好在Javascript中附加一个单独的事件侦听器。 It's good practice to separate your HTML and Javascript code. 最好将HTML和Javascript代码分开。 I see you're using JQuery, so you do this in your Javascript like so: 我看到您正在使用JQuery,因此您可以在Javascript中执行以下操作:

$( 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. 其次,在您的validate函数中,您需要阻止表单的默认操作,即提交并重定向到操作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. HTML表单将始终尝试将其发布为默认操作,因此要使其进行其他操作(例如验证),则必须积极阻止其发布。

You do this in JQuery by editing your validateForm function to prevent the form's default action with event.preventDefault. 您可以在JQuery中通过编辑validateForm函数来执行此操作,以防止使用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. 对于错误,必须首先将错误变量设置为false(假设一切都很好),并在发现错误时将其更改为true。 If it's still false after the checks, there were no errors. 如果检查后仍然为假,则没有错误。

Your Javascript function should look like this: 您的Javascript函数应如下所示:

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. 完成这些更改后,您的表单将不会执行操作,并且您的validateForm函数应运行,检查错误,如果没有,则使ajax POST进入processContactEmail.php。

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

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