簡體   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