基本上我正在使用本教程:HTML FORM
一切都正常工作,但我发现的一个流程是每个人都可以看到 .php
的 URL
,在本例中为“url:” contact_mail.php""
当有人输入 url
并按 Enter 键时,有没有办法保护我的表单不被空白提交。
示例: www.mywebsite.com/contact_mail.php
谢谢!
最佳答案
首先您可以使用required
客户端必填字段的属性:
<input type="text" name="mandatory_field" required>
但是您需要验证服务器端,以防用户修改表单。您可以使用empty()
任何变量($_POST
或 $_GET
):
if (empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
您可以使用isset()
验证字段是否已提交。您的验证可能是:
if (!isset($_POST['mandatory_field']) || empty($_POST['mandatory_field'])) {
// print error message or redirect to form page
}
其他情况:
如果所有字段都是必填字段,您可以使用in_array()
进行检查。 :
if (in_array(false, $_POST)) {
// print error message or redirect to form page
}
如果在这里进行各种数据验证是我对表单所做的事情:
$errors = [
'empty field' => empty($_POST['field']),
'another error message' => $another_condition
];
if (in_array(true, $errors)) {
$error_message = array_search(true, $errors);
// print or redirect, and you can tell the user what is wrong
}
关于javascript - 如何防止 HTML 表单提交空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51021062/