春風(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)論排行榜

          Web頁面表單域驗(yàn)證方式的改進(jìn)

          首先感謝CSDN網(wǎng)友hbhbhbhbhb1021的幫助,否則我現(xiàn)在可能還卡在正則表達(dá)式的特殊處理上。

          我們對(duì)網(wǎng)頁表單域驗(yàn)證常采取JS驗(yàn)證的方式,即取得某個(gè)表單域的值,然后對(duì)它進(jìn)行正則表達(dá)式驗(yàn)證,如果通過則進(jìn)行下一項(xiàng)驗(yàn)證,否則顯示出錯(cuò)文字并置上焦點(diǎn),具體代碼如下:

          <script LANGUAGE="JavaScript">
          <!
          /**
          * text has text Check
          */
          function hasText(str){
            
          return str.length>0;
          }
          function $(id){
               
          return document.getElementById(id);
          }
          /**
          * Character Check
          */
          function isCharacter(str){
            
          var regex=new RegExp("^[\u4E00-\u9FA5]+$");
            
          return regex.test(str);
          }

          /**
          * 新建主題前檢查
          */
          function check(){
            
          // 取得主題名(必填字段)
            var name=$("name").value;

            
          // 主題名非空檢查
            if(hasText(name)==false){
              $(
          "name").focus();
              $(
          "nameMsg").className="feedbackShow";
              
          return false;
            }
            
          else{
              $(
          "nameMsg").className="feedbackHide";
            }
          // 取得主題分類(非必填字段)
            var topicclass=$("topicclass").value;

            
          // 主題分類非空檢查
            if(hasText(topicclass)==true){
              
          if(isCharacter(topicclass)==false){
                $(
          "topicclass").focus();
                $(
          "topicclassMsg").className="feedbackShow";
                
          return false;
              }
              
          else{
                $(
          "topicclassMsg").className="feedbackHide";
              }
            }
           
           
            
          // 取得主題內(nèi)容(必填字段)
            var concept=$("concept").value;
           
            
          // 主題內(nèi)容非空檢查
            if(hasText(concept)==false){
              $(
          "concept").focus();
              $(
          "conceptMsg").className="feedbackShow";
              
          return false;
            }
            
          else{
              $(
          "conceptMsg").className="feedbackHide";
            }
           
            
          return true;
          }

          //-->
          </script>

          這種做法當(dāng)然湊效,但這樣的頁面寫多了或者表單字段多了也容易讓人煩躁,除了具體的正則表達(dá)式不同,其他代碼明顯有大量的重復(fù)工作,而且表現(xiàn)和行為也未完全分離。能否將它改進(jìn)一下呢?本文將探討一下新的方法。

          首先,我們可以發(fā)現(xiàn),具體的驗(yàn)證正則表達(dá)式是和單個(gè)表單域在一起的,如果把表達(dá)式也放在表單域中,驗(yàn)證時(shí)只需過來取即可,無須要專門準(zhǔn)備一個(gè)函數(shù)。具體寫法如下:
          <input type="text" 
                 name
          ="code" 
                 validChar
          ="\d{4}" 
                 isRequired
          ="true" 
                 onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                 onblur
          ="this.style.backgroundColor='#ffffff'"/>
          <font color=red>&nbsp;(必填)</font>
          <span id="codeMsg" class="feedbackHide">員工號(hào)必須輸入四位數(shù)字</span>
          在上面,我給文本框加入了一個(gè)自定義的屬性,validChar,用它來放置正則表達(dá)式。

          其次,請(qǐng)大家注意span那句:
          <span id="codeMsg" class="feedbackHide">員工號(hào)必須輸入四位數(shù)字</span>
          這里我特意把其ID做成是文本框ID加上字符串“Msg”,這樣出錯(cuò)時(shí)找到這個(gè)span并改變其顯示狀態(tài)就更方便了。

          具體驗(yàn)證一個(gè)文本框的函數(shù)如下:
          /**
          * 檢查文本框
          */
          function checkTextBox(vTextBox){
              
          // 取得文本框中允許輸入的合法文字正則表達(dá)式
              var validChar=vTextBox.getAttribute("validChar");
              
              
          // 取得文本框中是否必須檢查的標(biāo)志
              var isRequired=vTextBox.getAttribute("isRequired");
              
              
          // 取得文本框的輸入
              var inputValue=vTextBox.value;
              
              
          if(isRequired!="true" && inputValue.length<1){
                  
          // 如果是非必填字段且沒有輸入則返回真
                  return true;
              }
              
          else{
                  
          // 否則進(jìn)行正則表達(dá)式驗(yàn)證
                  //alert("表達(dá)式為"+validChar);
                  //alert("驗(yàn)證的字符串為"+inputValue);
                  var regexStr="^"+validChar+"$";
                  
          var regex=new RegExp(regexStr);
                  
          return regex.test(inputValue);
              }
          }

          使用了這樣的寫法后,批量調(diào)用對(duì)表單中諸文本框的檢查成為可能,而且也沒有什么重復(fù)代碼了,檢查Form的函數(shù)如下:
          /**
          * 提交前檢查
          */
          function check(vform){
              
          // 遍歷表單中每個(gè)表單域
              for(var i=0;i<vform.elements.length;i++){        
                  
          if(vform.elements[i].type=="text"){
                      
          // 如果表單域是文本框的話,進(jìn)行定義好的驗(yàn)證
                      
                      
          // 取得驗(yàn)證結(jié)果
                      var checkResult=checkTextBox(vform.elements[i]);
                      
          // alert(checkResult);
              
                      
          // 取得文本框名
                      var name=vform.elements[i].getAttribute("name");            
                      
                      
          if(checkResult){
                          
          // 驗(yàn)證通過
                          document.getElementById(name+"Msg").className="feedbackHide";
                      }
                      
          else{        
                          
          // 驗(yàn)證不通過,顯示提示文字并置焦點(diǎn)    
                          document.getElementById(name+"Msg").className="feedbackShow";
                          vform.elements[i].focus();
                          
          return false;
                      }                
                  }
              }
           
              
          return true;
          }

          而這兩個(gè)函數(shù)都是一個(gè)通用過程,可以放在一個(gè)JS的實(shí)用類中,這樣做的最大好處就是頁面中可以減少很多JS代碼,我們也能減輕很多重復(fù)性很高的擔(dān)子了。

          所有代碼如下,請(qǐng)注意其中的正則表達(dá)式,其中雙斜杠的地方都變成了單斜杠,前面沒有轉(zhuǎn)義字符/,這是因?yàn)閺捻撁嫒〕鰰r(shí)JS就幫忙給轉(zhuǎn)了,當(dāng)然其它場(chǎng)合轉(zhuǎn)不轉(zhuǎn)還要具體情況具體分析(感謝CSDN網(wǎng)友hbhbhbhbhb1021的幫助):
          <%@ page contentType="text/html; charset=UTF-8"%>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>JavaScript驗(yàn)證表單字段</title>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
              type
          ="text/css" />
          </head>

          <body>
              
          <div id="bodyDiv">
                  
          <div id="header">
                      
          <jsp:include page="/web/page/branch/header.jsp"/>
                  
          </div>
                  
          <div id="sidebar">
                      
          <jsp:include page="/web/page/branch/sidebar.jsp"/>
                  
          </div>
                  
          <div id="content">
                      
          <!-- 外層表格,比內(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="630" align="center" border="0">
                          
          <tr bgcolor="#eaecf5" height="25">
                          
          <td colspan=3>&nbsp;<font face=webdings color=#ff8c00>8</font><b>&nbsp;請(qǐng)?zhí)钊雮€(gè)人信息</b></td>
                          
          </tr>
                          
          <tr bgcolor=#236d78 height=1><td></td></tr>
                          
          <tr bgcolor=#eaecf5 >
                          
          <td bgcolor=#ffffff>
                            
          <!-- 內(nèi)置表格,居中,比外表格窄, -->
                            
          <form action="#" onsubmit="return check(this);">
                            
          <table width=560 align=center border=0>
                              
          <tbody>
                                
          <tr>
                                  
          <td width=70>員工號(hào):</td>
                                  
          <td>
                                      
          <input type="text" 
                                             name
          ="code" 
                                             validChar
          ="\d{4}" 
                                             isRequired
          ="true" 
                                             onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                             onblur
          ="this.style.backgroundColor='#ffffff'"/>
                                      
          <font color=red>&nbsp;(必填)</font>
                                      
          <span id="codeMsg" class="feedbackHide">員工號(hào)必須輸入四位數(shù)字</span>
                                  
          </td>
                                
          </tr>
                                
          <tr>
                                  
          <td width=70>姓名:</td>
                                  
          <td>
                                      
          <input type="text" 
                                             name
          ="name" 
                                             validChar
          ="[\u4E00-\u9FA5]{2,3}"  
                                             isRequired
          ="true" 
                                             onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                             onblur
          ="this.style.backgroundColor='#ffffff'"/>
                                      
          <font color=red>&nbsp;(必填)</font>
                                      
          <span id="nameMsg" class="feedbackHide">姓名必須輸入兩到三位漢字</span>
                                  
          </td>
                                
          </tr>
                                
          <tr>
                                  
          <td width=70>郵件:</td>
                                  
          <td>
                                      
          <input type="text" 
                                             name
          ="mail" 
                                             validChar
          ="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
                                             isRequired
          ="true" 
                                             onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                             onblur
          ="this.style.backgroundColor='#ffffff'"/>
                                      
          <font color=red>&nbsp;(必填)</font>
                                      
          <span id="mailMsg" class="feedbackHide">輸入必須符合郵件地址格式,如XX@XXX.XX</span>
                                  
          </td>
                                
          </tr>
                                
          <tr>
                                  
          <td width=70>費(fèi)用:</td>
                                  
          <td>
                                      
          <input type="text" 
                                             name
          ="expense" 
                                             validChar
          ="\d+(\.\d{0,2})*" 
                                             isRequired
          ="false" 
                                             onfocus
          ="this.style.backgroundColor='#e6e6e6'" 
                                             onblur
          ="this.style.backgroundColor='#ffffff'"/>
                                      
          <span id="expenseMsg" class="feedbackHide">請(qǐng)輸入合法的費(fèi)用格式,如1.23</span>
                                  
          </td>
                                
          </tr>           
                                
          <tr>
                                  
          <td></td>
                                  
          <td><input type="submit" value="提交"/></td>
                                
          </tr>
                              
          </tbody>          
                            
          </table>
                            
          </form>
                            
          <!-- 內(nèi)置表格結(jié)束-->
                          
          </td> 
                        
          </tr>
                      
          </table>
                      
          <!-- 外層表格結(jié)束 -->
                  
          </div>
                  
          <div id="footer">
                      
          <jsp:include page="/web/page/branch/footer.jsp"/>
                  
          </div>
              
          </div>
          </body>
          </html>

          <script LANGUAGE="JavaScript">
          <!--

          /**
          * 提交前檢查
          */
          function check(vform){
              
          // 遍歷表單中每個(gè)表單域
              for(var i=0;i<vform.elements.length;i++){        
                  
          if(vform.elements[i].type=="text"){
                      
          // 如果表單域是文本框的話,進(jìn)行定義好的驗(yàn)證
                      
                      
          // 取得驗(yàn)證結(jié)果
                      var checkResult=checkTextBox(vform.elements[i]);
                      
          // alert(checkResult);
              
                      
          // 取得文本框名
                      var name=vform.elements[i].getAttribute("name");            
                      
                      
          if(checkResult){
                          
          // 驗(yàn)證通過
                          document.getElementById(name+"Msg").className="feedbackHide";
                      }
                      
          else{        
                          
          // 驗(yàn)證不通過,顯示提示文字并置焦點(diǎn)    
                          document.getElementById(name+"Msg").className="feedbackShow";
                          vform.elements[i].focus();
                          
          return false;
                      }                
                  }
              }
           
              
          return true;
          }

          /**
          * 檢查文本框
          */
          function checkTextBox(vTextBox){
              
          // 取得文本框中允許輸入的合法文字正則表達(dá)式
              var validChar=vTextBox.getAttribute("validChar");
              
              
          // 取得文本框中是否必須檢查的標(biāo)志
              var isRequired=vTextBox.getAttribute("isRequired");
              
              
          // 取得文本框的輸入
              var inputValue=vTextBox.value;
              
              
          if(isRequired!="true" && inputValue.length<1){
                  
          // 如果是非必填字段且沒有輸入則返回真
                  return true;
              }
              
          else{
                  
          // 否則進(jìn)行正則表達(dá)式驗(yàn)證
                  //alert("表達(dá)式為"+validChar);
                  //alert("驗(yàn)證的字符串為"+inputValue);
                  var regexStr="^"+validChar+"$";
                  
          var regex=new RegExp(regexStr);
                  
          return regex.test(inputValue);
              }
          }

          //-->
          </script>


          CSS定義:
          .feedbackShow{
          visibility
          : visible;
          }

          .feedbackHide
          {
          visibility
          : hidden;
          }


          posted on 2008-04-06 16:50 sitinspring 閱讀(2830) 評(píng)論(4)  編輯  收藏 所屬分類: Web開發(fā)

          評(píng)論

          # re: Web頁面表單域驗(yàn)證方式的改進(jìn) 2008-04-06 16:56 千里冰封

          不錯(cuò),挺有用的,呵呵,方便多了  回復(fù)  更多評(píng)論   

          # re: Web頁面表單域驗(yàn)證方式的改進(jìn) 2008-04-06 20:55 cash

          太麻煩了吧,不如用額外的JS驗(yàn)證庫搞定。  回復(fù)  更多評(píng)論   

          # re: Web頁面表單域驗(yàn)證方式的改進(jìn) 2008-04-07 09:58 lifw

          自定義的屬性(validChar)在firefox下也可用嗎?
            回復(fù)  更多評(píng)論   

          # re: Web頁面表單域驗(yàn)證方式的改進(jìn) 2008-04-07 10:53 漠漠

          @lifw
          很明顯,是可用的  回復(fù)  更多評(píng)論   

          sitinspring(http://www.aygfsteel.com)原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處.
          主站蜘蛛池模板: 志丹县| 德钦县| 临海市| 蓬溪县| 旬邑县| 双牌县| 罗甸县| 诸暨市| 东乌| 闽清县| 元阳县| 乐都县| 崇文区| 夏津县| 内江市| 大理市| 雷波县| 宜君县| 屯门区| 保定市| 宜兰县| 遂川县| 进贤县| 瓦房店市| 南通市| 扎兰屯市| 博罗县| 静乐县| 疏勒县| 芦山县| 河池市| 衢州市| 共和县| 无锡市| 西盟| 肥乡县| 西林县| 蒙城县| 鹤山市| 彩票| 垦利县|