表单问题的PHP验证

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (54)

我整天都在进行这种表格验证,我几乎就在那里,但它还不对。有人告诉我在w3schools使用这个例子我做了但它没有用。我搞砸了一段时间,现在它确实有效,但有些事情仍然搞砸了。如果有超过1个错误,则不会显示。只显示最后一个出现。其次,我希望它通过页面上的输入显示错误。目前它是一个空白页面,只是回应错误。我尝试将它们包含在表单的html中,但它不起作用。我使用的例子是:

https://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_complete

我的代码如下

HTML:

   <form class="form inline d-flex justify-content-center" action="contact.php" method="POST" role="form">
             <br style="clear:both">
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="first_name" name="first_name" placeholder="First Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="email" name="email" placeholder="Email" required>
                <span class="error">* <?php echo $emailErr;?></span>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="last_name" name="last_name" placeholder="Last Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="phone" name="phone" placeholder="Phone" required>
                <span class="error">* <?php echo $phoneErr;?></span>
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <textarea name="message" class="control" id="message" placeholder="What's on your mind?" rows="3"></textarea>
              </div>
              <button type="submit" id="submit" name="submit" class="btn btn-primary">SEND</button>
          </form>

PHP:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $message    = $_POST['message'];

    if (empty($first_name)) {
        $nameErr = "First name is required";
    } else {
        $first_name = check_input($first_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
            $error = "Only letters and white space allowed";
        } else {
            $pass += 1;
        }
    }

    if (empty($last_name)) {
        $nameErr = "Last name is required";
    } else {
        $last_name = check_input($last_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
            $error = "Only letters and white space allowed";
        }else {
            $pass += 1;
        }
    }

    if (empty($email)) {
        $emailErr = "Email is required";
    } else {
        $email = check_input($email);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format";
        }else {
            $pass += 1;
        }
    }

    if (empty($phone)) {
        $phoneErr = "Phone number is required";
    } else {
        $phone = check_input($phone);

        if (!preg_match("'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'",$phone)) {
            $error = "Invalid Phone Number";
        }else {
            $pass += 1;
        }
    }

    if (empty($message)) {
        $error = "Message  cannot be blank";
    } else {
        $message = check_input($message);
        $pass += 1;
    }
}

$email_from =' Client, llc';
$email_subject = 'New Message From A Guest';
$email_body = "Name: $first_name $last_name\n".
              "Email: $email\n".
              "Phone: $phone\n".
              "Message: $message.\n";
$to ="me@work.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";

if (!isset($error) && $pass == '5'){
    mail($to,$email_subject,$email_body,$headers);
    header("location: thanks.html");
} else {
    echo $error;
}

// purge the session after it is displayed
unset($error);

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

我不认为电话检查工作正常,但我可以尝试不同的preg_match。我只需要让它正常工作。

提问于
用户回答回答于

每次发生错误时,您都会覆盖$ error中的值。您需要将新错误消息附加到现有错误。此外,如果您希望在输入旁边显示错误消息,则需要将错误消息放在相应的错误变量中。

更新html中姓氏错误的ID:

 <form class="form inline d-flex justify-content-center" action="contact.php" method="POST" role="form">
             <br style="clear:both">
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="first_name" name="first_name" placeholder="First Name" required>
                <span class="error">* <?php echo $nameErr;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="email" name="email" placeholder="Email" required>
                <span class="error">* <?php echo $emailErr;?></span>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <input type="text" class="control" id="last_name" name="last_name" placeholder="Last Name" required>
                <span class="error">* <?php echo $nameErr2;?></span>
              </div>
              <div class="form-group">
                <input type="text" class="control" id="phone" name="phone" placeholder="Phone" required>
                <span class="error">* <?php echo $phoneErr;?></span>
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <textarea name="message" class="control" id="message" placeholder="What's on your mind?" rows="3"></textarea>
              </div>
              <button type="submit" id="submit" name="submit" class="btn btn-primary">SEND</button>
          </form>

试试这个PHP:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $first_name = $_POST['first_name'];
    $last_name  = $_POST['last_name'];
    $email      = $_POST['email'];
    $phone      = $_POST['phone'];
    $message    = $_POST['message'];
    $error = ''; //init error to empty string
    $pass = 0; // init pass to 0;

    if (empty($first_name)) {
        $nameErr = "First name is required";
    } else {
        $first_name = check_input($first_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
            $nameErr = "Only letters and white space allowed";
            $error.='<p>'.$nameErr.'</p>';

        } else {
            $pass += 1;
        }
    }

    if (empty($last_name)) {
        $nameErr2 = "Last name is required";
    } else {
        $last_name = check_input($last_name);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
            $nameErr2 = "Only letters and white space allowed";
            $error.='<p>'.$nameErr2.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($email)) {
        $emailErr = "Email is required";
    } else {
        $email = check_input($email);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
            $error.='<p>'.$emailErr.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($phone)) {
        $phoneErr = "Phone number is required";
    } else {
        $phone = check_input($phone);

        if (!preg_match("'^(([\+]([\d]{2,}))([0-9\.\-\/\s]{5,})|([0-9\.\-\/\s]{5,}))*$'",$phone)) {
            $phoneErr = "Invalid Phone Number";
            $error.='<p>'.$phoneErr.'</p>';
        }else {
            $pass += 1;
        }
    }

    if (empty($message)) {
        $msgErr = "Message  cannot be blank";
        $error.='<p>'.$msgErr.'</p>';
    } else {
        $message = check_input($message);
        $pass += 1;
    }
}

$email_from =' Client, llc';
$email_subject = 'New Message From A Guest';
$email_body = "Name: $first_name $last_name\n".
              "Email: $email\n".
              "Phone: $phone\n".
              "Message: $message.\n";
$to ="me@work.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";

if ($error == '' && $pass == '5'){
    mail($to,$email_subject,$email_body,$headers);
    header("location: thanks.html");
} else {
    echo $error;
}

// purge the session after it is displayed
unset($error);

function check_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

扫码关注云+社区

领取腾讯云代金券