春風博客

          春天里,百花香...

          導航

          <2008年4月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          統計

          公告

          MAIL: junglesong@gmail.com
          MSN: junglesong_5@hotmail.com

          Locations of visitors to this page

          常用鏈接

          留言簿(11)

          隨筆分類(224)

          隨筆檔案(126)

          個人軟件下載

          我的其它博客

          我的鄰居們

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          表單驗證方式的通用化

          此文是“Web頁面表單域驗證方式的改進”的續篇。

          在上一篇“Web頁面表單域驗證方式的改進“中,我們通過把驗證法則(正則表達式和是否必填字段)寫在表單域中,將驗證過程和驗證法則成功的分離,從而減少了重復代碼,使驗證變得簡單易行,在實際使用中,我們可以把驗證過程放在一個JS文件中,對于全輸入驗證界面,在頁面的表單驗證部分只需要調用其中的checkForm函數就能進行有效驗證,頁面上不再需要書寫重復性高的JS驗證代碼;對于復雜的表單,比如其中含有復選框或是需要兩個文本框比較的地方,這種方法也可讓你不寫通用驗證代碼而把主要精力放在特殊的驗證上。這些能減輕不少工作量,讓繁瑣的工作變得輕松愉快起來。

          下面我們看一看這種用法的實際使用。

          首先,我們可以把驗證過程放在一個JS文件中,具體代碼如下:
          formchecker.js
          /**
          * Check form
          */

          function checkForm(vform){
              
          for(var i=0;i<vform.elements.length;i++){        
                  
          if(vform.elements[i].type=="text"){
                      
          var checkResult=checkTextBox(vform.elements[i]);
                      
          var name=vform.elements[i].getAttribute("name");            
                      
                      
          if(checkResult){
                          document.getElementById(name
          +"Msg").className="feedbackHide";
                      }

                      
          else{        
                          document.getElementById(name
          +"Msg").className="feedbackShow";
                          vform.elements[i].focus();
                          
          return false;
                      }
                          
                  }

              }

           
              
          return true;
          }


          /**
          * Check text field in the form
          */

          function checkTextBox(vTextBox){
              
          var validChar=vTextBox.getAttribute("validChar");
              
          var isRequired=vTextBox.getAttribute("isRequired");
              
          var inputValue=vTextBox.value;
              
              
          if(isRequired!="true" && inputValue.length<1){
                  
          return true;
              }

              
          else{
                  
          var regexStr="^"+validChar+"$";
                  
          var regex=new RegExp(regexStr);
                  
          return regex.test(inputValue);
              }

          }


          /**
          * Remove Extra Char in textbox
          */

          function removeExtraChar(vTextBox,event){
              
          var maxlength=parseInt(vTextBox.getAttribute("maxlength"));
              
          var inputValue=vTextBox.value;
              
              
          if(inputValue.length>=maxlength){
                  event.keyCode
          =9;
              }

          }

          下面想驗證一個用戶登錄頁面,它的頁面部分代碼如下:
          <%@ page contentType="text/html; charset=UTF-8" %>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>"我的事務備忘錄"用戶登錄頁面</title>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <script src="web/js/ajax.js" type="text/javascript"></script>
          <script src="web/js/formchecker.js" type="text/javascript"></script>
          <link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
              type
          ="text/css" />
          </head>

          <body>
          <div id="branding">
              
          <%
                  
          String msg = (String) request.getAttribute("Msg");
                  
          if (msg != null) {
                      out.print(msg);
                  }
              
          %>
              
          <!-- 外層表格,比內表格寬,以在左右留出一定空當 -->
              
          <table style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid; border-bottom: 1px solid; boder_top: 0px" bordercolor="#236d78" cellspacing="0" cellpadding="0" width="530" align="center" border="0">
                  
          <tr bgcolor="#eaecf5" height="25">
                  
          <td colspan=3>&nbsp;<font face=webdings color=#ff8c00>8</font><b>&nbsp;用戶登錄:</b></td>
                  
          </tr>
                  
          <tr bgcolor=#236d78 height=1><td></td></tr>
                  
          <tr bgcolor=#eaecf5 >
                  
          <td bgcolor=#ffffff>
                    
          <!-- 內置表格,居中,比外表格窄, -->
                    
          <form action="UserLogin" onsubmit="return checkForm(this);">
                    
          <table width=460 align=center border=0>
                      
          <tbody>
                        
          <tr>
                          
          <td width=70>用戶名:</td>
                          
          <td>
                              
          <input type="text" 
                                     name
          ="userName" 
                                     validChar
          ="[\u4E00-\u9FA5]{2,3}" 
                                     isRequired
          ="true" 
                                     maxlength
          ="8" 
                                     onkeydown
          ="removeExtraChar(this,event)" 
                                     onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                     onblur
          ="this.style.backgroundColor='#ffffff'"/>
                              
          <font color=red>&nbsp;(必填)</font>
                              
          <span id="userNameMsg" class="feedbackHide">用戶名必須輸入兩到三位漢字</span>
                          
          </td>
                        
          </tr>
                        
          <tr>
                          
          <td width=70>密碼:</td>
                          
          <td>
                              
          <input type="text" 
                                     name
          ="userPswd" 
                                     validChar
          ="\w+"  
                                     isRequired
          ="true" 
                                     maxlength
          ="8" 
                                     onkeydown
          ="removeExtraChar(this,event)" 
                                     onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                     onblur
          ="this.style.backgroundColor='#ffffff'"/>
                              
          <font color=red>&nbsp;(必填)</font>
                              
          <span id="userPswdMsg" class="feedbackHide">密碼必須輸入英語或數字</span>
                          
          </td>
                        
          </tr>    
                        
          <tr>
                          
          <td></td>
                          
          <td><input type="submit" value="登錄"/></td>
                        
          </tr>
                        
          <tr>
                          
          <td colspan="2" align="center">如果沒有用戶請點擊這里<href='ShowPage?page=register'>注冊</a></td>
                        
          </tr>
                      
          </tbody>          
                    
          </table>
                    
          </form>
                    
          <!-- 內置表格結束-->
                  
          </td> 
                
          </tr>
              
          </table>
              
          <!-- 外層表格結束 -->
          <div>
          </body>
          </html>

          請注意其中沒有任何頁面驗證的JS代碼,只有在表單驗證的地方調用formchecker.js中的函數。
          <form action="UserLogin" onsubmit="return checkForm(this);">

          不需要寫JS代碼,只需要引入formchecker.js,就實現了表單的驗證,下面是驗證效果之一:



          對于復雜一些的頁面,在formchecker.js的幫助下也能有效減少驗證代碼量,你只要書寫一些特殊的通過validchar不能驗證的代碼即可,比如說如下注冊頁面:


          你只要書寫兩次密碼比較的JS代碼,其它的還是可以讓checkForm函數幫你完成。具體代碼如下:
          <%@ page contentType="text/html; charset=UTF-8" %>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>"我的事務備忘錄"用戶注冊頁面</title>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <script src="web/js/ajax.js" type="text/javascript"></script>
          <script src="web/js/formchecker.js" type="text/javascript"></script>
          <link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
              type
          ="text/css" />
          </head>

          <body>
          <div>
          <%
              
          String msg = (String) request.getAttribute("Msg");
              
          if (msg != null) {
                  out.print(msg);
              }
          %>
              
          <!-- 外層表格,比內表格寬,以在左右留出一定空當 -->
              
          <table style="border-right: 1px solid; border-top: 1px solid; border-left: 1px solid; border-bottom: 1px solid; boder_top: 0px" bordercolor="#236d78" cellspacing="0" cellpadding="0" width="530" align="center" border="0">
                  
          <tr bgcolor="#eaecf5" height="25">
                  
          <td colspan=3>&nbsp;<font face=webdings color=#ff8c00>8</font><b>&nbsp;注冊個人用戶</b></td>
                  
          </tr>
                  
          <tr bgcolor=#236d78 height=1><td></td></tr>
                  
          <tr bgcolor=#eaecf5 >
                  
          <td bgcolor=#ffffff>
                    
          <!-- 內置表格,居中,比外表格窄, -->
                    
          <form action="UserRegister" onsubmit="return check(this);">
                    
          <table width=460 align=center border=0>
                      
          <tbody>
                        
          <tr>
                          
          <td width=70>用戶名:</td>
                          
          <td>
                              
          <input type="text" 
                                     name
          ="userName" 
                                     validChar
          ="[\u4E00-\u9FA5]{2,3}" 
                                     isRequired
          ="true" 
                                     onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                     onblur
          ="this.style.backgroundColor='#ffffff'"/>
                              
          <font color=red>&nbsp;(必填)</font>
                              
          <span id="userNameMsg" class="feedbackHide">用戶名必須輸入兩到三位漢字</span>
                          
          </td>
                        
          </tr>
                        
          <tr>
                          
          <td width=70>密碼:</td>
                          
          <td>
                              
          <input type="text" 
                                     name
          ="userPswd" 
                                     validChar
          ="\w+"  
                                     isRequired
          ="true" 
                                     onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                     onblur
          ="this.style.backgroundColor='#ffffff'"/>
                              
          <font color=red>&nbsp;(必填)</font>
                              
          <span id="userPswdMsg" class="feedbackHide">密碼必須輸入英語或數字</span>
                          
          </td>
                        
          </tr>   
                        
          <tr>
                          
          <td width=70>再次輸入密碼:</td>
                          
          <td>
                              
          <input type="text" 
                                     name
          ="userPswd2" 
                                     validChar
          ="\w+"  
                                     isRequired
          ="true" 
                                     onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                     onblur
          ="this.style.backgroundColor='#ffffff'"/>
                              
          <font color=red>&nbsp;(必填)</font>
                              
          <span id="userPswd2Msg" class="feedbackHide">密碼必須輸入英語或數字</span>
                          
          </td>
                        
          </tr>   
                        
          <tr>
                          
          <td></td>
                          
          <td><input type="submit" value="注冊"/></td>
                        
          </tr>
                      
          </tbody>          
                    
          </table>
                    
          </form>
                    
          <!-- 內置表格結束-->
                  
          </td> 
                
          </tr>
              
          </table>
              
          <!-- 外層表格結束 -->
          <div>
          </body>
          </html>

          <script LANGUAGE="JavaScript">
          <!--
          function check(vform){
              
          // 先進行文本框基本驗證
              if(checkForm(vform)==false){
                  
          return false;
              }

              
          // 取得密碼
              var userPswd=$("userPswd").value;
              
              
          // 取得第二次密碼
              var userPswd2=$("userPswd2").value;
              
              
          // 檢查兩次密碼是否對應
              if(userPswd2!=userPswd){
                  alert(
          "兩次輸入的密碼不相同");
                  $(
          "userPswd2").focus();
                  
          return false;
              }
              
              
          return true;
          }
          //-->
          </script>


          注意看上面的js代碼比常規方案減少了多少。

          如果頁面上有其它控件如復選框,列表框等也可照此辦理,把文本框的通用驗證交給formchecker.js的checkForm和checkTextBox進行,在頁面的js代碼中只寫特殊的處理,這樣能減輕不少工作量,讓繁瑣的工作變得輕松愉快起來。

          posted on 2008-04-07 21:41 sitinspring 閱讀(2342) 評論(7)  編輯  收藏 所屬分類: Web開發JavaScript

          評論

          # re: 表單驗證方式的通用化 2008-04-07 23:11 王能

          http://www.bt285.cn 這個BT網站,與http://yaonba.com.cn NBA中文網
          表單也是用這個的說.  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-04-08 13:52 BeanSoft

          建議看看 EasyValidation 思路差不多,不過貌似它們做的更模塊化一些,呵呵。  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-04-08 21:49 如坐春風

          @BeanSoft

          你推薦的EasyValidation很有參考價值,應該從其中汲取營養。謝謝推薦。  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-04-09 12:51 javaest

          我在考慮通過對JAVA對象的標注,生成前端JS的驗證代碼,同時服務器端也可以通過標注去驗證CLICENT端傳來的數據是否正確,這樣,兩個數據層面的驗證得到了統一和極大的簡化  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-04-10 08:37 如坐春風

          @javaest

          是否類似Struts的Validator的做法?  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-05-08 10:11 龍震

          <input />元素增加很多冗余的屬性,W3C validation 無法通過,我不知道作者是否關注這方面的問題?賜教!  回復  更多評論   

          # re: 表單驗證方式的通用化 2008-05-08 11:30 如坐春風

          @龍震

          客氣了!

          驗證的方便性和標準化確實不能兼顧,為方便性考慮只能先顧一頭了.沒有辦法.  回復  更多評論   

          sitinspring(http://www.aygfsteel.com)原創,轉載請注明出處.
          主站蜘蛛池模板: 镇宁| 鄂伦春自治旗| 洞口县| 长乐市| 外汇| 礼泉县| 枣阳市| 蒙自县| 莎车县| 江都市| 聂荣县| 麻栗坡县| 正定县| 屏东县| 酒泉市| 新营市| 安龙县| 聂拉木县| 子洲县| 安化县| 正镶白旗| 临沂市| 宁安市| 石柱| 临潭县| 长汀县| 台北县| 夏河县| 明水县| 兴海县| 龙口市| 大关县| 承德县| 秭归县| 阜新| 辛集市| 淄博市| 蕲春县| 上饶市| 平顶山市| 古丈县|