JavaScript实现指定格式字符串表单校验
运行效果:
源代码:
1 <!DOCTYPE html>
2 <html lang="zh">
3 <head>
4 <meta charset="UTF-8">
5 <title>表单</title>
6 </head>
7 <body>
8 <form action="" method="post" onsubmit="return validate();">
9 <label for="userName">姓名:</label><input type="text" name="userName" id="userName" value="Polaris"/><br/>
10 <label for="card">卡号:</label><input type="text" name="card" id="card"/><br/>
11 <button type="submit">发送</button>
12 </form>
13
14 <script type="text/javascript">
15 function validate() {
16 if (!checkName(document.getElementById("userName").value)) return false;
17 if (!checkNum(document.getElementById("card").value)) return false;
18 alert("数据完全");
19 return true;
20 }
21
22 function checkName(s) {
23 var ok = (s.length > 0);
24 if (!ok) alert("名字输入有误,请查核!");
25 return ok;
26 }
27
28 function checkNum(n) {
29 var ok, i, ch;
30 ok = (n.charAt(4) === "-" && n.charAt(9) === "-" && n.charAt(14) === "-");
31 if (!ok) {
32 alert("<" + n + "> 卡号输入有误,请查核!");
33 return false;
34 }
35 i = 0;
36 while (i < 19) {
37 ch = n.charAt(i);
38 if (ch !== "-" && (ch > "9" || ch < "0")) {
39 alert("<" + n + "> 卡号输入有误,查核!");
40 return false;
41 }
42 i++;
43 }
44 return true;
45 }
46
47 </script>
48 </body>
49 </html>