php - 需要在表单页面上显示纯 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"]);
}
}
解决方案
推荐阅读
- c - C中的空字符常量
- javascript - Django:即使在设置 enctype=multipart/form-data 之后,文件也没有在请求中传递?
- python - 如何从 selenium 和 python 中的文件对话框中选择文件
- java - 循环中的 JavaFX LineChart 会随时间增加内存使用量
- javascript - RegEx 用于提取字符串中的分散数字
- c# - 当一个方法返回一个 TaskCompletionSource 的 .Task 是什么意思
多变的? - android - 使用Flutter,在Android 20以下运行谷歌地图时,它不起作用..有什么想法吗?
- javascript - 检查 http 标头以查看是否可以在 iframe 中加载 url
- email - 可以通过向单个收件人发送大量电子邮件来提高电子邮件发件人的声誉吗?
- javascript - 如何在jquery数据表的渲染函数中添加if条件