学习W3SCHOOL 表单验证

 1 //表单学习笔记
 2 //建立一张表单的验证
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6     <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
 7     <title>表单验证</title>
 8 </head>
 9 <body>
10 <?php
11 //创建一个检查函数
12 
13 
14 function test_input($data){
15     $data=trim($data);
16     $data=stripslashes($data);
17     $data=htmlspecialchars($data);
18     return $data;
19 }
20 if(!empty($_POST['submit'])){
21 // 定义变量并设置为空值
22 $nameErr = $emailErr = $genderErr = $websiteErr = "";
23 $name = $email = $gender = $comment = $website = "";
24 
25 if ($_SERVER["REQUEST_METHOD"] == "POST") {
26   if (empty($_POST["name"])) {
27     $nameErr = "Name is required";
28   } else {
29     $name = test_input($_POST["name"]);
30   }
31   if(!preg_match("/^[a-zA-Z ]*$/", $name)){
32        $nameErr="只允许字母和空格!";
33     }
34 
35   if (empty($_POST["email"])) {
36     $emailErr = "Email is required";
37   } else {
38     $email = test_input($_POST["email"]);
39   }
40   if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)){
41         $emailErr = "无效的 email 格式!"; 
42     }
43 
44   if (empty($_POST["website"])) {
45     $website = "";
46   } else {
47     $website = test_input($_POST["website"]);
48   }
49   if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
50 =~_|]/i",$website)) {
51         $websiteErr = "无效的 URL"; 
52     }
53 
54   if (empty($_POST["comment"])) {
55     $comment = "";
56   } else {
57     $comment = test_input($_POST["comment"]);
58   }
59 
60   if (empty($_POST["gender"])) {
61     $genderErr = "Gender is required";
62   } else {
63     $gender = test_input($_POST["gender"]);
64   }
65 }
66 }
67 ?>
68 
69 <h2>PHP表单验证</h2>
70 <p style="color:#ff0000">*必填字段</p>
71 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>">
72 <p>姓名:<input type="text" name="name"><span style="color:#ff0000">*</span><?php echo $nameErr?></p>
73 <p>邮箱:<input type="text" name="email"><span style="color:#ff0000">*</span><?php echo $emailErr?></p>
74 <p>网址:<input type="text" name="website"><?php echo $websiteErr?></p>
75 <p>评论:<textarea name="comment" rows="5" cols="40"></textarea></p>
76 <p>性别:<input type="radio" name="gender" value="female">女性<input type="radio" name="gender" value="male">男性<span style="color:#ff0000">*</span><?php echo $genderErr?></p>
77 <p><input type="submit" name="submit" value="提交"></p>
78 </form>
79 <h2>您的输入:</h2>
80 
81 
82 </body>
83 </html>

 

posted @ 2015-01-28 17:01  luwenjie  阅读(485)  评论(0编辑  收藏  举报