<?php
// 定义变量并初始化为空
$name = $email = $url = $gender = $nameErr = $emailErr = $urlErr = $genderErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 验证姓名
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// 检查姓名是否只包含字母和空格
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
// 验证电子邮件
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// 检查电子邮件地址的格式
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// 验证URL
if (empty($_POST["url"])) {
$urlErr = "URL is required";
} else {
$url = test_input($_POST["url"]);
// 检查URL的格式
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$urlErr = "Invalid URL format";
}
}
// 验证性别
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
// 如果没有错误,可以进一步处理表单数据,例如将其保存到数据库中
}
function test_input($data) {
// 去除空格、斜杠和HTML标签
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form Validation</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<span class="error"><?php echo $nameErr; ?></span>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<span class="error"><?php echo $emailErr; ?></span>
<br>
<label for="url">URL:</label>
<input type="text" id="url" name="url">
<span class="error"><?php echo $urlErr; ?></span>
<br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male"> Male
<input type="radio" id="female" name="gender" value="female"> Female
<span class="error"><?php echo $genderErr; ?></span>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
在这个例子中,我们使用了HTML和PHP混编的方式,确保表单的action属性指向当前的PHP脚本(htmlspecialchars($_SERVER["PHP_SELF"]))。在表单中,我们添加了性别的选择框,并使用input元素的type属性为性别创建了单选按钮。
在CSS中,我们添加了一个简单的样式以将错误消息的文字颜色设为红色。
这只是一个基本的例子,实际项目中可能需要更多的验证规则、错误处理和安全性措施。
转载请注明出处:http://www.pingtaimeng.com/article/detail/3415/PHP