春風(fēng)博客

          春天里,百花香...

          導(dǎo)航

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

          統(tǒng)計(jì)

          公告

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

          Locations of visitors to this page

          常用鏈接

          留言簿(11)

          隨筆分類(224)

          隨筆檔案(126)

          個(gè)人軟件下載

          我的其它博客

          我的鄰居們

          最新隨筆

          搜索

          積分與排名

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          表單驗(yàn)證方式的通用化

          此文是“Web頁面表單域驗(yàn)證方式的改進(jìn)”的續(xù)篇。

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

          下面我們看一看這種用法的實(shí)際使用。

          首先,我們可以把驗(yàn)證過程放在一個(gè)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;
              }

          }

          下面想驗(yàn)證一個(gè)用戶登錄頁面,它的頁面部分代碼如下:
          <%@ page contentType="text/html; charset=UTF-8" %>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>"我的事務(wù)備忘錄"用戶登錄頁面</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);
                  }
              
          %>
              
          <!-- 外層表格,比內(nèi)表格寬,以在左右留出一定空當(dāng) -->
              
          <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>
                    
          <!-- 內(nèi)置表格,居中,比外表格窄, -->
                    
          <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">密碼必須輸入英語或數(shù)字</span>
                          
          </td>
                        
          </tr>    
                        
          <tr>
                          
          <td></td>
                          
          <td><input type="submit" value="登錄"/></td>
                        
          </tr>
                        
          <tr>
                          
          <td colspan="2" align="center">如果沒有用戶請(qǐng)點(diǎn)擊這里<href='ShowPage?page=register'>注冊(cè)</a></td>
                        
          </tr>
                      
          </tbody>          
                    
          </table>
                    
          </form>
                    
          <!-- 內(nèi)置表格結(jié)束-->
                  
          </td> 
                
          </tr>
              
          </table>
              
          <!-- 外層表格結(jié)束 -->
          <div>
          </body>
          </html>

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

          不需要寫JS代碼,只需要引入formchecker.js,就實(shí)現(xiàn)了表單的驗(yàn)證,下面是驗(yàn)證效果之一:



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


          你只要書寫兩次密碼比較的JS代碼,其它的還是可以讓checkForm函數(shù)幫你完成。具體代碼如下:
          <%@ page contentType="text/html; charset=UTF-8" %>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>"我的事務(wù)備忘錄"用戶注冊(cè)頁面</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);
              }
          %>
              
          <!-- 外層表格,比內(nèi)表格寬,以在左右留出一定空當(dāng) -->
              
          <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;注冊(cè)個(gè)人用戶</b></td>
                  
          </tr>
                  
          <tr bgcolor=#236d78 height=1><td></td></tr>
                  
          <tr bgcolor=#eaecf5 >
                  
          <td bgcolor=#ffffff>
                    
          <!-- 內(nèi)置表格,居中,比外表格窄, -->
                    
          <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">密碼必須輸入英語或數(shù)字</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">密碼必須輸入英語或數(shù)字</span>
                          
          </td>
                        
          </tr>   
                        
          <tr>
                          
          <td></td>
                          
          <td><input type="submit" value="注冊(cè)"/></td>
                        
          </tr>
                      
          </tbody>          
                    
          </table>
                    
          </form>
                    
          <!-- 內(nèi)置表格結(jié)束-->
                  
          </td> 
                
          </tr>
              
          </table>
              
          <!-- 外層表格結(jié)束 -->
          <div>
          </body>
          </html>

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

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


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

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

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

          評(píng)論

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

          http://www.bt285.cn 這個(gè)BT網(wǎng)站,與http://yaonba.com.cn NBA中文網(wǎng)
          表單也是用這個(gè)的說.  回復(fù)  更多評(píng)論   

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

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

          # re: 表單驗(yàn)證方式的通用化 2008-04-08 21:49 如坐春風(fēng)

          @BeanSoft

          你推薦的EasyValidation很有參考價(jià)值,應(yīng)該從其中汲取營(yíng)養(yǎng)。謝謝推薦。  回復(fù)  更多評(píng)論   

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

          我在考慮通過對(duì)JAVA對(duì)象的標(biāo)注,生成前端JS的驗(yàn)證代碼,同時(shí)服務(wù)器端也可以通過標(biāo)注去驗(yàn)證CLICENT端傳來的數(shù)據(jù)是否正確,這樣,兩個(gè)數(shù)據(jù)層面的驗(yàn)證得到了統(tǒng)一和極大的簡(jiǎn)化  回復(fù)  更多評(píng)論   

          # re: 表單驗(yàn)證方式的通用化 2008-04-10 08:37 如坐春風(fēng)

          @javaest

          是否類似Struts的Validator的做法?  回復(fù)  更多評(píng)論   

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

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

          # re: 表單驗(yàn)證方式的通用化 2008-05-08 11:30 如坐春風(fēng)

          @龍震

          客氣了!

          驗(yàn)證的方便性和標(biāo)準(zhǔn)化確實(shí)不能兼顧,為方便性考慮只能先顧一頭了.沒有辦法.  回復(fù)  更多評(píng)論   

          sitinspring(http://www.aygfsteel.com)原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處.
          主站蜘蛛池模板: 正定县| 岐山县| 永济市| 横山县| 英德市| 高州市| 宽城| 芜湖市| 西华县| 荣成市| 贵定县| 白沙| 通河县| 青冈县| 清原| 巴青县| 资兴市| 古田县| 鹤岗市| 济宁市| 东至县| 广灵县| 钦州市| 肇州县| 泸州市| 竹溪县| 深泽县| 凤台县| 乌什县| 烟台市| 安塞县| 五大连池市| 禹城市| 泽普县| 定襄县| 灌云县| 苏州市| 海安县| 太仆寺旗| 九江县| 莆田市|