本章介绍如何将输入字段设置为必填字段并在需要时创建错误消息。
从上一页的验证规则表中,我们看到 "Name"、"E-mail" 和 "Gender" 字段是必填字段。这些字段不能为空,必须在 HTML 表单中填写。
Field | Validation Rules |
---|---|
Name | Required. + Must only contain letters and whitespace |
Required. + Must contain a valid email address (with @ and .) | |
Website | Optional. If present, it must contain a valid URL |
Comment | Optional. Multi-line input field (textarea) |
Gender | Required. Must select one |
在上一章中,所有输入字段都是可选的。
在以下代码中,我们添加了一些新变量:$nameErr、$emailErr、$genderErr 和 $websiteErr。这些错误变量将保存必填字段的错误消息。我们还添加了一个if else
每个 $_POST 变量的语句。这会检查 $_POST 变量是否为空(使用 PHPempty()
功能)。如果为空,则将错误消息存储在不同的错误变量中,如果不为空,则通过test_input()
功能:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
然后在 HTML 表单中,我们在每个必填字段后添加一个小脚本,如果需要,它会生成正确的错误消息(即如果用户尝试在不填写必填字段的情况下提交表单):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
运行示例 »
下一步是验证输入数据,即 "Does the Name field contain only letters and whitespace?" 和 "Does the E-mail field contain a valid e-mail address syntax?",如果填写,则为 "Does the Website field contain a valid URL?"。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!