php - 使用 PHP 进行表单验证不起作用
问题描述
我对 PHP 很陌生,我正在尝试使用三个输入字段验证一个简单的表单。出于某种原因,当我在字段为空时单击提交按钮时,我什么也没有返回。我已经为这个问题苦苦挣扎了好几个小时了。
我想要实现的是在字段为空/无效时在字段旁边获取错误文本。
这是我的 HTML 和 PHP 代码。
HTML:
<form method="post" action="">
<table width="450px">
<tr>
<td valign="top">
<label for="nimi">Nimi</label>
</td>
<td valign="top">
<td><input type="text" name="nimi"><span class="error"><?php echo $nimiVirhe;?></span></td>
</td>
</tr>
<tr>
<td valign="top">
<label for="sposti">Sähköposti</label>
</td>
<td valign="top">
<td><input type="text" name="sposti"><span class="error"><?php echo $spostiVirhe;?></span></td>
</td>
</tr>
<tr>
<td valign="top">
<label for="palaute">Palaute</label>
</td>
<td valign="top">
<textarea name="palaute" maxlength="1000" cols="30" rows="6"></textarea><span class="error"><?php echo $palauteVirhe;?> </span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Lähetä" name="submit">
</td>
</tr>
</table>
</form>
PHP
<?php
$nimiVirhe = $spostiVirhe = $palauteVirhe = "";
$nimi = $sposti = $palaute = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nimi"])) {
$nimiVirhe = "Name is required";
} else {
$nimi = test_input($_POST["nimi"]);
if (!preg_match("/^[a-zA-Z ]*$/",$nimi)) {
$nimiVirhe = "Only letters and white space allowed";
}
}
if (empty($_POST["sposti"])) {
$spostiVirhe = "Contact is required";
} else {
$sposti = test_input($_POST["sposti"]);
if (!filter_var($sposti, FILTER_VALIDATE_EMAIL)) {
$spostiVirhe = "Invalid email format";
}
}
if (trim($_POST["palaute"]) == "") {
$palauteVirhe = "City is required";
} else {
$palaute = test_input($_POST["palaute"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
我不知道下一步该尝试什么。
我在这里先向您的帮助表示感谢!
解决方案
推荐阅读
- c++ - 如何在此处使用模板以避免在此代码中使用 std::function
- pandas - 将 gzip 压缩的 csv 导入 pandas
- file - 通过 Direct WiFi 将 SD 数据直接从 Wemos D1 复制到笔记本电脑
- python - 将日期时间对象从 JSON 修改为 utc
- c# - 从集合中删除所有条目,这些条目使用 linq 在不同的集合中找到
- mongodb - MongoDB - 使用索引自动完成搜索
- python - Tensorflow 和 tensorboard:使用多个模型拟合运行可视化图形
- google-analytics - 在 Reporting API v4 上请求自定义维度“userType”时缺少 ga:source 的一些行
- angular - 使用angular7滚动到ng2-tree的选定节点
- python - Pandas:即使日期已经在月末,也能正确获取业务月末日期