表单验证方式的通用化

Posted on 2008-04-07 21:41 博学精思慎言笃行 阅读(1030) 评论(7)  编辑  收藏 所属分类: Web开发JavaScript
此文是“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;
    }

    
//