繁体   English   中英

使用验证码验证联系表

[英]Validating Contact Form with Captcha

我有一个联系方式,里面有一个人字。 提交邮件没有问题,但是我遇到的问题是验证并将值传输到提交处理程序。 我对PHP和Javascript的了解有限。 我虚心寻求您的帮助来检查这些代码,并告诉我需要做些什么才能使其正确。 任何帮助将不胜感激!

以下是邮件处理程序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;
}

?>

这是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>

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

第一个问题似乎是您的验证函数在HTML中被称为validate();

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

但是在您的Javascript中,定义的函数称为validateForm() 要解决此问题,只需确保它们被称为同一事物(无所谓,只要它们匹配即可)。

而不是通过onSubmit="return validate();"内联调用验证函数onSubmit="return validate();" ,最好在Javascript中附加一个单独的事件侦听器。 最好将HTML和Javascript代码分开。 我看到您正在使用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
});

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

您可以在JQuery中通过编辑validateForm函数来执行此操作,以防止使用event.preventDefault进行表单的默认操作。 对于错误,必须首先将错误变量设置为false(假设一切都很好),并在发现错误时将其更改为true。 如果检查后仍然为假,则没有错误。

您的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

            }
        });
    }
}

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

暂无
暂无

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

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