2.5.4 表单的验证
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>表单验证</title>
<style>
.error {color:#FF0000;}
</style>
</head>
<body>
<?php
//定义变量并默认设置为空值
$nameErr=$emailErr=$genderErr=$websiteErr="";
$name=$email=$gender=$comment=$website="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
if(empty($_POST["name"]))
{
$nameErr="姓名是必须的";
}
else
{
$nameErr=test_input($_POST["name"]);
//检测名字是否只包含字母和空格
if(!preg_match("/^[a-zA-Z]*$/",$name))
{
$nameErr="名字只能包含字母和空格";
}
}
if(empty($_POST["email"]))
{
$emailErr="邮箱是必须的";
}
else
{
$email=test_input($_POST["email"]);
//检测邮箱是否合法
if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr="邮箱非法";
}
}
if(empty($_POST["website"]))
{
$website="";
}
else
{
$website=test_inut($_POST["website"]);
//检测URL地址是否合法
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="性别是必要的";
}
else
{
$gender=test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
<h2>表单验证:</h2>
<p><span class="error">*星号红色表示必需字段。</span></p>
<form method ="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
姓名:
<input type = "text" name = "name" value = "<?php echo $name;?>">
<span class = "error">*<?php echo $emailErr;?></span>
<br><br>
邮箱:
<input type = "text" name = "email" value = "<?php echo $email;?>">
<span class = "error">*<?php echo $emailErr;?></span>
<br><br>
网址:<input type = "text" name = "website" value="<?php echo $website;?>">
<span class = "error">*<?php echo $websiteErr;?></span>
<br><br>
说明:
<textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
性别:
<input type = "radio" name = "gender" <?php if(isset($gender) && $gender == "male") echo "checked";?> value = "male">
男
<input type = "radio" name = "gender" <?php if(isset($gender) && $gender == "female") echo "checked";?> value = "female">
女
<span class = "error">*<?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="提交验证">
</form>
<?php
echo "<h2>输入内容如下:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
在练习过程中出现了一些小问题,其中有些问题影响到了编译结果:
1、在php中< br >就是换行的意思,但是要注意与br搭配使用的是/而不是\,在书写时一定要注意区分/和\,二者有着本质上的区别。
2、input type在这段代码里有很多的应用,有comment,有text,有radio还有submit,他们分别对应text——文本框;comment——大文本框(下图中的说明);radio——选项;submit——按钮;
3、我们在网页编辑的时候经常会出现不同颜色的字样,这样的字样就是通过style来实现的。
我们首先定义了类error,然后直接给这个类中的所有对象赋予了红色的字体,操作相对简单,可见应该是最基本的字体颜色修改方式。
总结:通过上面的练习,我对php程序有了初步的了解,我将继续深入学习php,争取早日取得成绩!