春風博客

          春天里,百花香...

          導航

          <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頁面表單域驗證方式的改進

          首先感謝CSDN網友hbhbhbhbhb1021的幫助,否則我現在可能還卡在正則表達式的特殊處理上。

          我們對網頁表單域驗證常采取JS驗證的方式,即取得某個表單域的值,然后對它進行正則表達式驗證,如果通過則進行下一項驗證,否則顯示出錯文字并置上焦點,具體代碼如下:

          <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";
              }
            }
           
           
            
          // 取得主題內容(必填字段)
            var concept=$("concept").value;
           
            
          // 主題內容非空檢查
            if(hasText(concept)==false){
              $(
          "concept").focus();
              $(
          "conceptMsg").className="feedbackShow";
              
          return false;
            }
            
          else{
              $(
          "conceptMsg").className="feedbackHide";
            }
           
            
          return true;
          }

          //-->
          </script>

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

          首先,我們可以發現,具體的驗證正則表達式是和單個表單域在一起的,如果把表達式也放在表單域中,驗證時只需過來取即可,無須要專門準備一個函數。具體寫法如下:
          <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">員工號必須輸入四位數字</span>
          在上面,我給文本框加入了一個自定義的屬性,validChar,用它來放置正則表達式。

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

          具體驗證一個文本框的函數如下:
          /**
          * 檢查文本框
          */
          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{
                  
          // 否則進行正則表達式驗證
                  //alert("表達式為"+validChar);
                  //alert("驗證的字符串為"+inputValue);
                  var regexStr="^"+validChar+"$";
                  
          var regex=new RegExp(regexStr);
                  
          return regex.test(inputValue);
              }
          }

          使用了這樣的寫法后,批量調用對表單中諸文本框的檢查成為可能,而且也沒有什么重復代碼了,檢查Form的函數如下:
          /**
          * 提交前檢查
          */
          function check(vform){
              
          // 遍歷表單中每個表單域
              for(var i=0;i<vform.elements.length;i++){        
                  
          if(vform.elements[i].type=="text"){
                      
          // 如果表單域是文本框的話,進行定義好的驗證
                      
                      
          // 取得驗證結果
                      var checkResult=checkTextBox(vform.elements[i]);
                      
          // alert(checkResult);
              
                      
          // 取得文本框名
                      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;
          }

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

          所有代碼如下,請注意其中的正則表達式,其中雙斜杠的地方都變成了單斜杠,前面沒有轉義字符/,這是因為從頁面取出時JS就幫忙給轉了,當然其它場合轉不轉還要具體情況具體分析(感謝CSDN網友hbhbhbhbhb1021的幫助):
          <%@ page contentType="text/html; charset=UTF-8"%>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>JavaScript驗證表單字段</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">
                      
          <!-- 外層表格,比內表格寬,以在左右留出一定空當 -->
                      
          <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;請填入個人信息</b></td>
                          
          </tr>
                          
          <tr bgcolor=#236d78 height=1><td></td></tr>
                          
          <tr bgcolor=#eaecf5 >
                          
          <td bgcolor=#ffffff>
                            
          <!-- 內置表格,居中,比外表格窄, -->
                            
          <form action="#" onsubmit="return check(this);">
                            
          <table width=560 align=center border=0>
                              
          <tbody>
                                
          <tr>
                                  
          <td width=70>員工號:</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">員工號必須輸入四位數字</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>費用:</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">請輸入合法的費用格式,如1.23</span>
                                  
          </td>
                                
          </tr>           
                                
          <tr>
                                  
          <td></td>
                                  
          <td><input type="submit" value="提交"/></td>
                                
          </tr>
                              
          </tbody>          
                            
          </table>
                            
          </form>
                            
          <!-- 內置表格結束-->
                          
          </td> 
                        
          </tr>
                      
          </table>
                      
          <!-- 外層表格結束 -->
                  
          </div>
                  
          <div id="footer">
                      
          <jsp:include page="/web/page/branch/footer.jsp"/>
                  
          </div>
              
          </div>
          </body>
          </html>

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

          /**
          * 提交前檢查
          */
          function check(vform){
              
          // 遍歷表單中每個表單域
              for(var i=0;i<vform.elements.length;i++){        
                  
          if(vform.elements[i].type=="text"){
                      
          // 如果表單域是文本框的話,進行定義好的驗證
                      
                      
          // 取得驗證結果
                      var checkResult=checkTextBox(vform.elements[i]);
                      
          // alert(checkResult);
              
                      
          // 取得文本框名
                      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;
          }

          /**
          * 檢查文本框
          */
          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{
                  
          // 否則進行正則表達式驗證
                  //alert("表達式為"+validChar);
                  //alert("驗證的字符串為"+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 閱讀(2822) 評論(4)  編輯  收藏 所屬分類: Web開發

          評論

          # re: Web頁面表單域驗證方式的改進 2008-04-06 16:56 千里冰封

          不錯,挺有用的,呵呵,方便多了  回復  更多評論   

          # re: Web頁面表單域驗證方式的改進 2008-04-06 20:55 cash

          太麻煩了吧,不如用額外的JS驗證庫搞定。  回復  更多評論   

          # re: Web頁面表單域驗證方式的改進 2008-04-07 09:58 lifw

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

          # re: Web頁面表單域驗證方式的改進 2008-04-07 10:53 漠漠

          @lifw
          很明顯,是可用的  回復  更多評論   

          sitinspring(http://www.aygfsteel.com)原創,轉載請注明出處.
          主站蜘蛛池模板: 恩平市| 许昌县| 拉萨市| 辽宁省| 乐昌市| 襄汾县| 德江县| 鹤壁市| 五寨县| 三门县| 美姑县| 五指山市| 孟村| 寿宁县| 哈尔滨市| 菏泽市| 濮阳县| 通许县| 惠州市| 洞头县| 普兰店市| 收藏| 肃南| 高台县| 山丹县| 长沙县| 乐清市| 临城县| 湛江市| 深州市| 防城港市| 微博| 南安市| 科技| 汶上县| 即墨市| 揭阳市| 陆丰市| 峨眉山市| 三原县| 汽车|