//表单学习笔记
//建立一张表单的验证
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>表单验证</title>
</head>
<body>
<?php
//创建一个检查函数 function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if(!empty($_POST['submit'])){
// 定义变量并设置为空值
$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(!preg_match("/^[a-zA-Z ]*$/", $name)){
$nameErr="只允许字母和空格!";
} if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)){
$emailErr = "无效的 email 格式!";
} if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
=~_|]/i",$website)) {
$websiteErr = "无效的 URL";
} 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"]);
}
}
}
?> <h2>PHP表单验证</h2>
<p style="color:#ff0000">*必填字段</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>">
<p>姓名:<input type="text" name="name"><span style="color:#ff0000">*</span><?php echo $nameErr?></p>
<p>邮箱:<input type="text" name="email"><span style="color:#ff0000">*</span><?php echo $emailErr?></p>
<p>网址:<input type="text" name="website"><?php echo $websiteErr?></p>
<p>评论:<textarea name="comment" rows="5" cols="40"></textarea></p>
<p>性别:<input type="radio" name="gender" value="female">女性<input type="radio" name="gender" value="male">男性<span style="color:#ff0000">*</span><?php echo $genderErr?></p>
<p><input type="submit" name="submit" value="提交"></p>
</form>
<h2>您的输入:</h2> </body>
</html>