春风博客

春天里,百花香...

导航

<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 阅读(2797) 评论(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.blogjava.net)原创,转载请注明出处.