春风博客

春天里,百花香...

导航

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