1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>示例-表单校验-涉及的正则校验</title>
6 <style type="text/css">
7
8 </style>
9 </head>
10
11 <body>
12
13 <script type="text/javascript">
14 //发现很多框的校验除了几个内容不同外,校验的过程是一样的。
15 //所以进行了代码的提取。
16 function check(name,reg,spanId,okinfo,errinfo){
17
18 var flag;
19 var val = document.getElementsByName(name)[0].value;
20
21 var oSpanNode = document.getElementById(spanId);
22
23
24 if(reg.test(val)){
25 oSpanNode.innerHTML = okinfo.fontcolor("green");
26 flag = true;
27 }
28 else{
29 oSpanNode.innerHTML = errinfo.fontcolor("54r");
30 flag = false;
31 }
32 }
33
34 //校验用户名
35 function checkUser(){
36 var reg = /^[a-z]{4}$/i;
37 return check("user",reg,"userspan","用户名正确","用户名错误");
38 }
39
40 //校验密码
41 function checkPsw(){
42 var reg = /^\d{4}$/;
43 return check("psw",reg,"pswspan","密码正确","密码错误");
44 }
45
46 //校验确定密码。只要和密码一致即可
47 function checkRepsw(){
48 var flag;
49 //获取密码框内容
50 var pass = document.getElementsByName("psw")[0].value;
51 //获取确认密码框内容
52 var repass = document.getElementsByName("repsw")[0].value;
53
54 //获取确认密码的span区域
55 var oSpanNode = document.getElementById("repswspan");
56
57 if(pass==repass){
58 oSpanNode.innerHTML="两次密码一致".fontcolor("green");
59 flag = true;
60 }
61 else{
62 oSpanNode.innerHTML="两次密码不一致".fontcolor("red");
63 flag = false;
64 }
65
66 }
67
68 //校验邮件
69 function checkMail(){
70 var reg = /^\[email protected]\w+(\.\w)+$/i;
71 return check("mail",reg,"mailspan","邮件地址正确","邮件地址错误");
72 }
73
74 //提交事件处理
75 function checkForm(){
76 if(checkUser() && checkPsw() && checkRepsw() && checkMail())
77 return true;
78 return false;
79 }
80
81 //提交事件处理
82 function mySubmit(){
83 var oFormNode =document.getElementById("userinfo");
84
85 oFormNode.submit();
86 }// onsubmit="return checkForm()"
87 </script>
88 <!--表单校验-->
89 <form id="userinfo">
90 用户名称:<input type="text" name="user" onblur="checkUser()" />
91 <span id="userspan"></span>
92 <br/>
93 输入密码:<input type="password" name="psw" onblur="checkPsw()" />
94 <span id="pswspan"></span>
95 <br/>
96 确认密码:<input type="password" name="repsw" onblur="checkRepsw()" />
97 <span id="repswspan"></span>
98 <br/>
99 邮件地址:<input type="text" name="mail" onblur="checkMail()" />
100 <span id="mailspan"></span>
101 <br/>
102 <input type="submit" value="提交数据" />
103 </form>
104 <!--自定义提交按钮-->
105 <input type="button" value="我的提交" onclick="mySubmit()" />
106
107
108
109 </body>
110 </html>
时间: 2024-12-14 12:06:36