html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>php处理表单</title> </head> <body> <form action="biaodan.php" method="post"> <fieldset id=""> <legend>注册</legend> <p> <label>用户:<input type="text" name="name" /></label> </p> <p> <label for="email">邮箱:</label> <input type="text" name="email" id="email" /> </p> <p> 性别: <label><input type="radio" name="gender" value="male"/>帅哥</label> <label><input type="radio" name="gender" value="famale"/>美女</label> </p> <p> <label>年龄: <select name="age"> <option value="1">15~20</option> <option value="2">20~30</option> <option value="3">40~50</option> </select> </label> </p> <p>备注: <textarea name="comments" id="" cols="30" rows="10"></textarea> </p> </fieldset> <input type="submit" name="submit" value="提交" /> </form> </body> </html>
PHP:
<?php header( 'Content-Type:text/html;charset=utf-8 '); //验证用户名 //用isset()检测一个文本框是否有内容时,存在且不为null,返回true,无输入则是空字符,满足存在且不为null $name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null; if(empty($name)) { echo '<script>alert("您没有输入用户名");history.go(-1);</script>'; } elseif (!preg_match("/^[a-zA-Z ]*$/",$name)) { //preg_match — 执行匹配正则表达式 echo '<script>alert("用户名只能为数字和空格");</script>'; } else { echo '<script>alert("您的用户名是:'.$name.'");</script>'; } //验证邮箱 $email = isset($_REQUEST['email']) ? $_REQUEST['email'] : null; if(empty($email)) { echo '<script>alert("您没有输入邮箱");history.go(-1);</script>'; } elseif (!preg_match("/([\w\-]+@[\w\-]+\.[\w\-]+)/",$email)) { echo '<script>alert("您输入的邮箱格式不对!");</script>'; } else { echo '<script>alert("您的邮箱是:'.$email.'");</script>'; } //验证性别 $gender = isset($_REQUEST['gender']) ? $_REQUEST['gender'] : null; if(is_null($gender)) { echo '<script>alert("请您选择性别!");</script>'; } else { if ($gender == 'male') { echo '<script>alert("哈喽!帅哥!");</script>'; } elseif ($gender == 'famale') { echo '<script>alert("哈喽!美女!");</script>'; } } //验证年龄 $age = isset($_REQUEST['age']) ? $_REQUEST['age'] : null; if($age == 1) { echo '<script>alert("青少年");</script>'; } elseif ($age == 2) { echo '<script>alert("年轻人");</script>'; } elseif ($age == 3) { echo '<script>alert("中年人");</script>'; } //验证备注 $text = isset($_REQUEST['comments']) ? $_REQUEST['comments'] : null; if (empty($text)) { echo '<script>alert("请输入备注!");history.go(-1);</script>'; } else { echo '<script>alert("备注成功!");</script>'; } if ($name && $email && $gender && $password1) { echo '<script>alert("注册成功!");location.href="login.html";</script>'; } else { echo '<script>alert("验证失败,请检查~~");location.href="biaodan.php"</script>'; } ?>