需要在表单页面上显示纯PHP验证错误

时间:2019-06-18 20:55:14

标签: php

我有一个form.php脚本,该脚本通过HTML获取名称,电子邮件和消息并将其插入到数据库中,这没有问题。

但是,如果用户未能填写任何字段,我希望它显示一个简单的错误,例如“您什么都没告诉您”。

我的表单具有action =“ actions.php”,其中数据经过验证并传递到DB,然后重定向回form.php,因此用户实际上从那里看不到任何东西。

有什么方法可以使我的代码仅在PHP仅将字段留空的情况下显示上述错误?

我尝试了如果$ _SERVER [“ REQUEST_METHOD”] &&空($ _POST [“ name”])然后$ err =“请告知blablabla”; .php。它只是在form.php中不起作用,因为无论如何该表单都已发送到actions.php。

而且,如果我在form.php中需要actions.php,则会收到“重定向过多”错误。我实际上需要访问form.php中的$ nameErr变量。

我知道我可以处理actions.php中的所有内容并在那里显示任何数据,但是我认为这是一种不良的用户体验,因为他需要手动返回form.php才能重新输入数据。

以下是代码: form.php

<form class="center-div" method="post" action="actions.php">

<div class="field margin-bottom-small">Name</div> 
<input style="outline: none;" class="margin-bottom-small" type="text" name="name">
<span class="error"><?php echo $nameErr;  ?></span> <!-- Error here -->

<div class="field margin-bottom-small">Email</div> 
<input style="outline: none;" class="margin-bottom-small" type="text" name="email">

<div class="field margin-bottom-small">Message</div> 
<textarea style="outline: none;" class="margin-bottom-small" name="message" rows="5" columns="40"></textarea>

<input class="submit-button margin-bottom-small" type="submit" name="submit" value="Enviar">
</form>

Actions.php :test_input只是我用来清理输入数据的功能。

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

  if (empty($_POST["name"])) {
    $nameErr = "Please inform your name"; // my blank field error. 
    header("Location: form.php");
    // exit; 
  } else {
    $name = test_input($_POST["name"]);
  }


  if (empty($_POST["email"])) {

  } else {
    $email = test_input($_POST["email"]);
  }


  if (empty($_POST["message"])) {

  } else {
    $message = test_input($_POST["message"]);
  }
}

0 个答案:

没有答案