首页 > 解决方案 > 需要在表单页面上显示纯 PHP 验证错误

问题描述

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

但是,如果用户未能填写任何字段,我希望它显示一个简单的错误,例如“您没有通知您的任何内容”。

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

有没有什么办法可以让我的代码仅在只有 PHP 的字段留空时才显示上述错误?

我试过if $_SERVER["REQUEST_METHOD"] && empty($_POST["name"]) then $err = "Please inform blablabla"; 在actions.php 和form.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"]);
  }
}

标签: php

解决方案


推荐阅读