表单验证错误消息php

时间:2015-10-22 10:22:56

标签: php html validation

我有以下表格:

 <form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>" id="submit-form">
      <label for='fname'>Name</label>
      <input type='text' name="customer" value="" id="customer" maxlength='50'/>
      <?php echo "<h1>$errName</h1>" ?>
      <label for='fname'>Company Name</label>
      <input type='text' name="company" value="" id="company" maxlength='50' />
      <label for='email'>Email Address</label>
      <input type='text' name='email' value="" id='email' maxlength='50'/>
      <label for='number'>Telephone Number</label>
      <input type='text' name="phone" value="" id="phone" maxlength='20'/>
      <input type="hidden" name="campaign" id="campaign" value="Getting Started" maxlength='300'>
      <input type='submit' name="submit-btn" id="submit-btn" value='Send Request'/>
    </form>

当我提交时,我运行以下PHP

function validate_input($data, $type) {

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);

        switch ($type) {
            case "name": //letters 
                if (!preg_match('/^[a-zA-Z ]{2,80}+$/', $data)) {
                    $errName = "Name can only contain letters";
                    $errors = true;
                }
                break;
            case "email":
                if (!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $data)) {
                    $errEmail = "Email must be valid format";
                    $errors = true;
                }
                break;
            case "company": //letters and numbers
                if (!preg_match('/^[a-zA-Z0-9 ]{2,80}+$/', $data)) {
                    $errCompany = "Company can only contain letters or numbers";
                    $errors = true;
                }
                break;
            case "number": //digits, spaces and hypens
                if (!preg_match('/^[\d -.]*\d$/', $data)) {
                    $errNumber = "Phone must be valid format";
                    $errors = true;
                }
                break;
            case "campaign":
                if (!preg_match('/^[a-zA-Z0-9 ]{2,80}+$/', $data)) {
                    $errCampaign = "Campaign must be valid format";
                    $errors = true;
                }
                break;
        }
        return $data;
    }

    //Check form was submitted
    if (isset($_POST['submit-btn'])) {
        $errors = false;
        $errName = $errEmail = $errCompany = $errPhone = $errCampaign = "";
        $name = $email = $company = $phone = $campaign = "";
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $name = validate_input($_POST['customer'], "name");
            $email = validate_input($_POST['email'], "email");
            $company = validate_input($_POST['company'], "company");
            $phone = validate_input($_POST['phone'], "number");
            $campaign = validate_input($_POST['campaign'], "campaign");
        }

        if ($errors == false) {
            //Send email to sales team
            $to = "test@gmail.com";
            $from = $email;
            $subject = "Test Email";
            $message = "Customer Name: " . $name
                    . "\r\nEmail Address: " . $email
                    . "\r\nCompany: " . $company
                    . "\r\nPhone Number: " . $phone
                    . "\r\nCampaign Type: " . $campaign;
            $headers = "From: " . $from;
            mail($to, $subject, $message, $headers);

            //Send email to customer
            $to = $email;
            $from = "test@gmail";
            $subject = "Thank you for your Enquiry:";
            $message = "Dear " . $name . ",\r\nThank you for getting in contact. One of our team will be in touch with you shortly.";
            $headers = "From: " . $from;
            mail($to, $subject, $message, $headers);
        }
    }

我在显示name字段的错误消息时遇到问题。正则表达式只允许字母和空格。如果有人输入12348jack之类的输入,则$error变量应设置为true,并且不应发送电子邮件。

但是,每次执行此操作时,都会发送电子邮件,并且表单上不会显示任何错误消息。

有没有人能指出我在哪里出错?

非常感谢

3 个答案:

答案 0 :(得分:1)

我认为这是一个范围问题。

您的基础是创建此测试的电子邮件

 if ($errors == false) {

     ....

但您实际上从未在$errors中设置validate_input,因为它超出了范围。

我建议您更改函数以传递$errors变量。请注意使用&$

function validate_input($data, $type, &$errors) {

然后你的功能可以访问它。

所以你的验证电话将是

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = validate_input($_POST['customer'], "name", $errors);
    $email = validate_input($_POST['email'], "email", $errors);
    $company = validate_input($_POST['company'], "company", $errors);
    $phone = validate_input($_POST['phone'], "number", $errors);
    $campaign = validate_input($_POST['campaign'], "campaign", $errors);
}

答案 1 :(得分:0)

这是一个scope问题

您可以在验证功能中使用global关键字

function validate_input($data, $type) {
global $errors;
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
....

我也推荐@RiggsFolly解决方案

答案 2 :(得分:-1)

为什么不创建包含所有HTML代码的变量,然后通过echo输出到视频,因此如果您想创建验证并管理HTML代码。

$fields = array ('name'=> '<input type='text' name="customer" value="" id="customer" maxlength='50'/>'...[all your form components]...);

if(!empty($_POST)){
    $validate_input($postedData,$postedType);
}

在validate_input函数中创建错误数组

$this->errors['name'] = "Name can only contain letters" ;

然后你要渲染的地方

 $buffer = <form method="post" action=" htmlspecialchars($_SERVER['PHP_SELF']) " id="submit-form">
    foreach (fields as $key => $htmlCode){
        $buffer.= "<label>$key</label><".$htmlCode.">;
        if(!empty($this->errors[$key])
            $buffer.="<label class='error'>".$this->errors[$key]."</label>";

    }

这部分代码未经测试,但我希望我已经给了你这个想法