PHP。联系表格,错误更改文本区域的颜色,无需重定向

时间:2014-01-02 11:13:55

标签: php html css forms

我有联系表格,成功发送邮件到我的电子邮箱。但是,当用户输入无效数据(例如未输入电子邮件)时,用户会重定向到send_form_email.php并显示错误“请输入电子邮件等...”我需要指出如果发生错误,错误应该显示在同一个没有重定向和输入字段的窗口应该变成“红色”颜色(据我所知需要改变css样式,但如何正确地做?)。

这是我的联系表格:

contact form


以下是错误现在的样子: contact error


以下是错误的原因: should be


这是我的联系表单的一部分,“电子邮件”字段的样子如下:

<form name="contactform" class="form_row" method="post" action="send_form_email.php">

<table width="450px">
    <tr>

     <td valign="top">

      <label for="email">El. paštas: *</label>

     </td>

     <td valign="top">

      <input  type="text" class="contact_input" name="email" maxlength="80" size="30">

     </td>

    </tr>

这是contact_input风格:

input.contact_input{
width:225px;
height:18px;
float:left;
border:1px #d1e0ee solid;
background-color:#fee9a1;
color: #000;
}

这是发生错误后重定向的部分。

function died($error) {


    echo "We are very sorry, but there were error(s) found with the form you submitted. ";

    echo "These errors appear below.<br /><br />";

    echo $error."<br /><br />";

    echo "Please go back and fix these errors.<br /><br />";

    die();

}

更新

这是我的完整send_form_email.php

<?php


    if(isset($_POST['email'])) {



        // EDIT THE 2 LINES BELOW AS REQUIRED

        $email_to = "myMail@gmail.com";

        $email_subject = "Message from myPage";





        function died($error) {

                session_start();
        $_SESSION['error'] = $error;
        header('Location: contact.php');
        die();


        }


     if (!is_valid_email($_POST['email'])) {
        $error['email'] = 'email should be entered';
    }
        // validation expected data exists

        if(!isset($_POST['name']) ||

            !isset($_POST['email']) ||

            !isset($_POST['telephone']) ||

            !isset($_POST['comments'])) {

            died('We are sorry, but there appears to be a problem with the form you submitted.');       

        }



        $name = $_POST['name']; 

        $email_from = $_POST['email']; // required

        $telephone = $_POST['telephone']; // not required

        $comments = $_POST['comments']; // required



        $error_message = "";

        $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

      if(!preg_match($email_exp,$email_from)) {

        $error_message .= 'The Email Address you entered does not appear to be valid.<br />';

      }

        $string_exp = "/^[A-Za-z .'-]+$/";

      if(!preg_match($string_exp,$name)) {

        $error_message .= 'The First Name you entered does not appear to be valid.<br />';

      }


      if(strlen($comments) < 2) {

        $error_message .= 'The Comments you entered do not appear to be valid.<br />';

      }

      if(strlen($error_message) > 0) {

        died($error_message);

      }

        $email_message = "Pranešimas apačioje.\n\n";



        function clean_string($string) {

          $bad = array("content-type","bcc:","to:","cc:","href");

          return str_replace($bad,"",$string);

        }



        $email_message .= "Vardas: ".clean_string($name)."\n";

        $email_message .= "El. paštas: ".clean_string($email_from)."\n";

        $email_message .= "Tel. Nr.: ".clean_string($telephone)."\n";

        $email_message .= "Pranešimas: ".clean_string($comments)."\n";





    // create email headers

    $headers = 'From: '.$email_from."\r\n".

    'Reply-To: '.$email_from."\r\n" .

    'X-Mailer: PHP/' . phpversion();

    @mail($email_to, $email_subject, $email_message, $headers);  

    ?>



    <!-- include your own success html here -->



    Thank you for contacting us. We will be in touch with you very soon.



    <?php

    }

    ?>

2 个答案:

答案 0 :(得分:1)

您可以使用jQuery添加客户端验证,并使用Ajax

提交表单

假设你这样的html表格

<form id="myForm">    
<table>
    <tr>
         <td colspan="2"><div id="result"></div></td>
    </tr>
    <tr>
         <td valign="top"><label for="email">El. pa?tas: *</label></td>
         <td valign="top">
              <input id="fEmail"  type="text" class="contact_input" name="email" maxlength="80" size="30">
         </td>
    </tr>
    <tr>
         <td valign="top"></td>
         <td valign="top">
              <input id="btnSend" name="Send" type="button" value="Send"/>
             </td>
    </tr>
 </table>
 </form>

并将以下css添加到样式表

.input-error
{
    background-color: #AA0000 !important;
}

以及以下jQuery脚本

<script type="text/javascript">
       $('.error').hide();
       $('#btnSend').click(function () {
            $('.error').hide();

            var email = $("input#fEmail").val();

            if (email == "") {
                $("input#fEmail").focus();
                $("input#fEmail").addClass("input-error");
                return false
            }

            $.ajax({
                        type: "POST", 
                        url: "send_form_email.php", 
                        data: $('#myForm').serialize(), 
                        success: function (response) {
                            $('#result').html("<div class='success'>" + response + "</div>")
                        }, failed: function (response) {
                            $('#result').html("<div class='error'>" + response + "</div>");
                        }
            });
            return false
        });

答案 1 :(得分:0)

如果您想使用PHP进行服务器端验证:

首先,您需要在检查发布值时分配错误值,例如:

if (!is_valid_email($_POST['email'])) {
    $error['email'] = 'email should be entered';
}

然后,如果有任何错误,您应该将$ error传递给表单页面。 例如,使用session:

function died($error) {
    session_start();
    $_SESSION['error'] = $error;
    header('Location: form_page.php');
    die();
}

然后在您的表单页面中:

session_start();
if (isset($_SESSION['error']['email'])) {
    echo '<input  type="text" class="contact_input error" name="email" maxlength="80" size="30" value="' . $_SESSION['error']['email'] . '">';
} else {
    // empty input
}
session_destroy();

css:

.error
{
    background-color: red !important;
}

修改

send_form_email.php应如下所示:

<?php
if (isset($_POST['email'])) {
    $email_to = "myMail@gmail.com";
    $email_subject = "Message from myPage";

    if (!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {

        $error['form'] = 'We are sorry, but there appears to be a problem with the form you submitted.';
    }

    $name = $_POST['name'];
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required

    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

    if (!preg_match($email_exp, $email_from)) {
        $error['email'] = 'The Email Address you entered does not appear to be valid.';
    }

    $string_exp = "/^[A-Za-z .'-]+$/";
    if (!preg_match($string_exp, $name)) {
        $error['name'] = 'The First Name you entered does not appear to be valid.';
    }


    if (strlen($comments) < 2) {
        $error['comment'] = 'The Comments you entered do not appear to be valid.';
    }

    if (count($error) > 0) {
        died($error);
    }

    $email_message = "Pranešimas apačioje.\n\n";

    function clean_string($string)
    {
        $bad = array("content-type", "bcc:", "to:", "cc:", "href");
        return str_replace($bad, "", $string);
    }

    $email_message .= "Vardas: " . clean_string($name) . "\n";
    $email_message .= "El. paštas: " . clean_string($email_from) . "\n";
    $email_message .= "Tel. Nr.: " . clean_string($telephone) . "\n";
    $email_message .= "Pranešimas: " . clean_string($comments) . "\n";

    // create email headers

    $headers = 'From: ' . $email_from . "\r\n" .
        'Reply-To: ' . $email_from . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

    @mail($email_to, $email_subject, $email_message, $headers);
}

function died($error) {
    session_start();
    $_SESSION['error'] = $error;
    header('Location: contact.php');
    die();
}

这只是您在问题中contact.php中HTML的一部分:

<form name="contactform" class="form_row" method="post" action="send_form_email.php">
<?php
session_start();
if (isset($_SESSION['error']['form'])) {
    echo '<span class="error">' . $_SESSION['error']['form'] . '</span>';
}
?>
<table width="450px">
    <tr>
        <td valign="top">
            <label for="email">El. paštas: *</label>
        </td>
        <td valign="top">
<?php
if (isset($_SESSION['error']['email'])) {
    echo '<input  type="text" class="contact_input error" name="email" maxlength="80" size="30" value="' . $_SESSION['error']['email'] . '">';
} else {
    echo '<input  type="text" class="contact_input" name="email" maxlength="80" size="30">';
}
?>
        </td>
    </tr>
<?php
session_destroy(); // THIS SHOULD BE IN THE END OF THE FILE
?>

您应该将html部分重复到所有输入字段

请花点时间了解这一切。 Sėkmės!