1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html>
4 <html>
5 <head><%-- 告訴瀏覽器不要緩存 --%>
6 <meta http-equiv ="proma" content = "no-cache"/>
7 <meta http-equiv="cache-control" content="no cache" />
8 <meta http-equiv="expires" content="0" />
9 <meta charset="UTF-8">
10 <title>test</title><%--設置網頁標題 --%>
11 <style type="text/css">/*css樣式*/
12 body {
13 margin-left: 25%;/*設置整個頁面離瀏覽器左邊空25%*/
14 margin-right: 25%;/*設置整個頁面離瀏覽器右邊空25%*/
15 background-color: #F2F2F2;/*設置整個頁面背景顏色*/
16 }
17 div {
18 background-color: #97D775;/*設置div背景顏色*/
19 height: 2000px;/*設置div高度*/
20 }
21 </style>
22
23 <script type="text/javascript">/*js*/
24 function userName_yz() {/*當焦點離開時觸發此事件,驗證輸入名稱是否符合要求*/
25 var name = document.getElementById("name").value;/*根據id獲取相應節點,然后取value值*/
26 var span_1 = document.getElementById("span_1");/*根據id獲取相應節點*/
27 if(name.length <= 3 || name.length >= 10) {/*驗證輸入名稱是否符合要求*/
28 span_1.style.display="inline";/*第一種修改屬性樣式*/
29 span_1.style.color="red";
30 return false;/*為了后面表單提交返回的一個boolean類型*/
31 } else {
32 span_1.style.display="none";
33 return true;/*為了后面表單提交返回的一個boolean類型*/
34 }
35 }
36
37 function password_yz() {/*當焦點離開時觸發此事件,驗證輸入密碼是否符合要求*/
38 var password = document.getElementById("password").value;
39 var span_2 = document.getElementById("span_2");
40 if(password.length <= 3 || password.length >= 10) {
41 span_2.setAttribute("style", "display: inline");/*第二種修改屬性樣式*/
42 span_2.setAttribute("style", "color: red");
43 return false;/*為了后面表單提交返回的一個boolean類型*/
44 } else {
45 span_2.setAttribute("style", "display: none");
46 return true;/*為了后面表單提交返回的一個boolean類型*/
47 }
48 }
49
50 function onsubmit_yz() {/*當表單提交時觸發此事件,驗證所有的要求是否符合*/
51 if(!userName_yz()) {/*根據驗證名稱的返回boolean來判斷*/
52 alert("名稱輸入不合要求,請重新輸入!");/*提示用戶,名稱輸入不符合要求*/
53 return false;/*阻止表單提交的boolean值*/
54 } else if(!password_yz()) {
55 alert("密碼輸入不合要求,請重新輸入!");/*提示用戶,密碼輸入不符合要求*/
56 return false;/*阻止表單提交的boolean值*/
57 } else {
58 return true;/*全部驗證通過,給用戶提交*/
59 }
60 }
61 </script>
62 </head>
63 <body>
64 <div>
65 <form action="#" method="post" onsubmit="return onsubmit_yz()"><%--form表單,onsubmit是當表單提交時觸發的事件 --%>
66 名稱:<input id="name" type="text" name="userName" onblur="userName_yz()"/><%--onblur時當焦點離開時觸發的事件 --%>
67 <span id="span_1">要求大於3個字符且小於10個字符</span><%--要求提示 --%>
68 <br/>
69 密碼:<input id="password" type="password" name="password" onblur="password_yz()"/>
70 <span id="span_2">要求大於3個字符且小於10個字符</span>
71 <br/>
72 <input type="submit" value="提交"/><%--提交表單 --%>
73 </form>
74 </div>
75 </body>
76 </html>