很实用的通用JS表单验证,调用很简单。

很实用的通用JS表单验证,调用很简单。

在WEB开发过程中经常要对表单进行验证,每次都要写很长一串验证代码,感觉很麻烦。

于是写了这个通用表单验证代码,由于是初学者,所以难免有很多地方不完善,欢迎各位高手不吝指教,小弟感激不尽。

下一步准备加入Ajax验证功能,如果大家有好的建议,请通过QQ474003869与我交流。

js代码(validate.js):

[复制到剪切板]
CODE:
/**
------------------------validate.js------------------------
 ※【功能】表单验证类
 ※【作者】aixle
 ※【版本】1.3
 ※【版权】Copyright (C) 2009-2010 aixle All Rights Reserved. 
 ※【联系方式】email:[email protected] QQ:474003869
 ※【创建日期】2009/08/18
 ※【修改日期】2009/08/30
------------------------函数说明------------------------
 chk.reg:正则表达式;
 chk.config:待验证项目信息,对应项目说明:
    id:待验证项目的id.(类型:字符串,必填)
    tip:待验证项目的提示标题.(类型:字符串,必填)
    arr:待验证的项目,对应的内容分别是:(类型:数组,至少填一项)
        arr[0]待验证项目的正则表达式类型,即check.js中reg下面所对应的项目。如果不需要则为"".(类型:字符串)
        arr[1]待验证项目最少输入字符,如果不限制则为0.(类型:正整数)
        arr[2]待验证项目最大输入字符,如果不限制则为0.(类型:正整数)
        arr[3]待验证项目是否不能为空,是则为true,不限制则为"".(类型:字符串)
        arr[4]待验证项目内容与另一输入框内容是否相同,其中arr[4]为另一输入框的id,一般用于判断两次输入的密码是否相同.不判断则为""或者不填.(类型:字符串)
 chk.form:提交表单时验证,参数fm为表单的ID,调用方法为window.onload = chk.form(fm);
 chk.input:当前输入框内容验证,调用方法为window.onload = chk.form();
 chk.limit:判断输入值是否在(n, m)区间,对应参数:
         str:待验证的字符串;
        n:最小值;
        m:最大值.
 chk.showErr:返回验证信息,对应参数:
         obj:待验证项目组件名称,主要用于当前输入框内容验证;
        errs:错误信息,如果为输入框内容验证则在其后面显示当前项目验证信息,如果为表单提交验证则在弹出消息框内显示错误信息列表.
------------------------------------------------------
*/
function $(id){return typeof(id) === 'object' id:document.getElementById(id);}
function 
$C(tag){return typeof(tag) === 'object' tag:document.createElement(tag);}
function 
Trim(str){return str.replace(/(^\s*)|(\s*$)/g,"");}
var 
chk = {
    
reg:{
        
name:[/^[a-zA-Z]{1}[a-zA-Z0-9_\-]{1,}$/, "只能由字母、数字以及(-_)组成,必须以字母开头."],
        
pass:[/[a-zA-Z0-9]$/, "只能由字母和数字组成."],
        
str:[/^[0-9a-zA-Z_\u0391-\uFFE5]+$/, "只能由中文、字母、数字以及下划线组成."],
        
eng:[/^[A-Za-z]+$/, "只能输入英文字母."],
        
chs:[/^[\u4e00-\u9fa5]+$/, "只能输入中文."],
        
num:[/^\d+$/, "只能输入数字."],
        
mail:[/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, "格式不正确."],
        
qq:[/^[1-9]{1}[0-9]{4,10}$/, "必须由5-10个整数组成."],
        
msn:[/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, "格式不正确."],
        
phone:[/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/, "格式不正确."],
        
mobile:[/^((\(\d{2,3}\))|(\d{3}\-))?((13\d{9})|(159\d{8}))$/, "格式不正确."],
        
post:[/^[1-9]{1}[0-9]{5}$/, "格式不正确."],
        
card:[/(^\d{15}$)|(^\d{17}[0-9Xx]$)/, "格式不正确."],
        
url:[/^(((ht|f)tp(s?))\:\/\/)[a-zA-Z0-9]+\.[a-zA-Z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/, "不是有效的URL地址."],
        ip:[/^((\d{1,2}|1\d{1,2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{1,2}|2[0-4]\d|25[0-5])$/, "不是有效的IP地址."],
        date:[/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2})$/, "格式不正确."]
    },
    config:[], //chk.config = [{id:"obj.id", title:"tipTitle", arr:[chk.reg.item, minsize, maxsize, isnull, comregeID]}]
    form:function(fm){
        if (chk.config && $(fm)){
            $(fm).onsubmit = function(){
                var msg = "", n = 1, str, tip, rst, arr ,reg;
                for (i in chk.config){
                    str = Trim($(chk.config[i].id).value);
                    tip = chk.config[i].tip;
                    arr = chk.config[i].arr;
                    if (tip){
                        if (!str){
                            if (arr[3] === true) msg += "[" + (n++) + "]." + tip + "不能为空.\n";
                        }else{
                            reg = chk.reg[arr[0]];
                            if (arr[1] || arr[2]){
                                rst = chk.limit(str, arr[1], arr[2]);
                                if (rst !== "yes") msg += "[" + (n++) + "]." + tip + rst + "\n";
                            }
                            if (arr[4] && str !== $(arr[4]).value) {msg += "[" + (n++) + "]." + tip + "与上次输入内容不同." + "\n"}
                            if (reg && !reg[0].test(str)){msg += "[" + (n++) + "]." + tip + reg[1] + "\n";}
                        }
                    }
                    
                }
                if (msg){msg = "以下原因导致提交失败:\n" + msg;}
                return chk.showErr("", msg);
            }
        }
    },
    input:function(){
        var msg, obj, arr, reg, k;
        for (i in chk.config){
            $(chk.config[i].id).setAttribute("key", i);
            $(chk.config[i].id).onblur = function(){
                k = chk.config[this.getAttribute("key")];
                if (k.tip){
                    msg = "";
                    obj = $(k.id);
                    arr = k.arr;
                    if (!obj.value){
                        msg = (arr[3] === true) ? "不能为空!":"";
                    }else{
                        msg = "yes";
                        reg = chk.reg[arr[0]];
                        if (arr[1] || arr[2]) msg = chk.limit(obj.value, arr[1], arr[2]);
                        if (msg === "yes" && arr[4] && obj.value !== $(arr[4]).value) msg = "与上次输入内容不同.";
                        if (msg === "yes" && reg && !reg[0].test(obj.value)) msg = reg[1];
                    }
                    if (msg && msg !== "yes"){msg = k.tip + msg;}
                    chk.showErr(obj, msg);
                }
                obj.style.backgroundColor = "#EAFFCA";
            }
            $(chk.config[i].id).onfocus = function()
{$(chk.config[this.getAttribute("key")].id).style.backgroundColor "#FFF";}
        }
    },
    limit:function(str, n, m){
        if (str){
            var len = str.length;
            return (n > 0 && len < n && "不能少于" + n + "个字符.") || (m > 0 && len > m && "不能超过" + m + "个字符.") || "yes";
        }
    },
    showErr:function(obj, errs){
        if (!obj){
            if (errs){
                alert(errs);
                return false;
            }
        }else{
            if(!$("ck_" + obj.id)){
                var tips = 
$C("span");
                tips.setAttribute('id',"ck_" + obj.id);
                tips.style.color="#F00";
                tips.style.fontSize="12px";
                obj.parentNode.appendChild(tips);
            }
            var obj = $("ck_" + obj.id);
            switch (errs) {
                case "":
                    obj.innerHTML = "";
                    return true;
                case "yes":
                    obj.innerHTML = "&nbsp;<img src='js/yes.gif' style='vertical-align:middle;' />";
                    return true;
                default:
                    obj.innerHTML = "<br><img src='js/no.gif' style='vertical-align:middle;' />&nbsp;" + errs;
                    return false;
            }
        }
    }
} ;


调用示例(demo.html):

[复制到剪切板]
CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
title>JS表单验证测试 By Aixle</title>
<
script language="javascript" src="js/validate.js"><\/script>
<
script type="text/javascript">
/* 
 chk.config:待验证项目信息,对应项目说明:
    id:待验证项目的id.(类型:字符串,必填)
    tip:待验证项目的提示标题.(类型:字符串,必填)
    arr:待验证的项目,对应的内容分别是:(类型:数组,至少填一项)
        arr[0]待验证项目的正则表达式类型,即check.js中reg下面所对应的项目。如果不需要则为"".(类型:字符串)
        arr[1]待验证项目最少输入字符,如果不限制则为0.(类型:正整数)
        arr[2]待验证项目最大输入字符,如果不限制则为0.(类型:正整数)
        arr[3]待验证项目是否不能为空,是则为true,不限制则为"".(类型:字符串)
        arr[4]待验证项目内容与另一输入框内容是否相同,其中arr[4]为另一输入框的id,一般用于判断两次输入的密码是否相同.不判断则为""或者不填.(类型:字符串)
*/
chk.config = [
    {
id:"user_name"tip:"用户名",  arr:["name"212true]}, 
    {
id:"chs_name",  tip:"中文名",  arr:["chs"212true]},
    {
id:"eng_name",  tip:"英文名",  arr:["eng"412true]},
    {
id:"pwd",       tip:"密码",    arr:["pass"516true]},
    {
id:"pwd2",      tip:"确认密码"arr:[""516true"pwd"]},
    {
id:"email",     tip:"邮箱",    arr:["mail"00true]},
    {
id:"qq",        tip:"QQ号码",  arr:["qq"]},
    {
id:"msn",       tip:"MSN号码"arr:["msn"]},
    {
id:"telphone",  tip:"电话号码"arr:["phone"]},
    {
id:"mobile",    tip:"手机号码"arr:["mobile"]},
    {
id:"postcode",  tip:"邮政编码"arr:["post"]},
    {
id:"idcard",    tip:"身份证",   arr:["card"]},
    {
id:"homepage",  tip:"个人主页"arr:["url"]},
    {
id:"ip",        tip:"IP地址",   arr:["ip"]},
    {
id:"mdate",     tip:"加入日期"arr:["date"00true]}]
window.onload=function(){
    
chk.form("fm1"); //fm1为表单id
    
chk.input();
}
<\/
script>
<
style type="text/css">
body{
    
font-size:12px;
    
margin:10px auto;
    
padding:0;
    
line-height:16px;
    
background-color:#DBECC6;
}
th{
    
color:#060;
    
font-size:16px;
    
line-height:38px;
    
background-color:#6C0;
}
td{
    
color:#090;
    
padding-left:3px;
    
background-color:#D9FFB3;
}
td.title{
    
color:#9F0;
    
font-size:18px;
    
font-weight:bold;
    
background-color:#090;
}
.
input{
    
color:#090;
    
width:300px;
    
height:14px;
    
line-height:14px;
    
background-color:#EAFFCA;
    
border:1px dotted #619414;
}
</
style>
</
head>

<
body>
  <
form action="refer.php" method="post" name="fm1" id="fm1">
    <
table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#009900">
      <
tr>
        <
td height="30" colspan="2" align="center" class="title">JS表单验证测试 By <a href="mailto:[email protected]title="联系作者">Ryan</a></td>
        </
tr>
      <
tr>
        <
th width="120" align="right">*用户名:</th>
        <
td width="339"><input name="user_name" type="text" class="input" id="user_name" /></td>
      </
tr>
      <
tr>
        <
th align="right">*中文名:</th>
        <
td><input name="chs_name" type="text" class="input" id="chs_name" /></td>
      </
tr>
      <
tr>
        <
th align="right">*英文名:</th>
        <
td><input name="eng_name" type="text" class="input" id="eng_name" /></td>
      </
tr>
      <
tr>
        <
th align="right">*密码:</th>
        <
td><input name="pwd" type="text" class="input" id="pwd" /></td>
      </
tr>
      <
tr>
        <
th align="right">*确认密码:</th>
        <
td><input name="pwd2" type="text" class="input" id="pwd2" value="" /></td>
      </
tr>
      <
tr>
        <
th align="right">*邮箱:</th>
        <
td><input name="email" type="text" class="input" id="email" /></td>
      </
tr>
      <
tr>
        <
th align="right">QQ:</th>
        <
td><input name="qq" type="text" class="input" id="qq" /></td>
      </
tr>
      <
tr>
        <
th align="right">MSN:</th>
        <
td><input name="msn" type="text" class="input" id="msn" /></td>
      </
tr>
      <
tr>
        <
th align="right">电话:</th>
        <
td><input name="telphone" type="text" class="input" id="telphone" /></td>
      </
tr>
      <
tr>
        <
th align="right">手机:</th>
        <
td><input name="mobile" type="text" class="input" id="mobile" /></td>
      </
tr>
      <
tr>
        <
th align="right">邮政编码:</th>
        <
td><input name="postcode" type="text" class="input" id="postcode" /></td>
      </
tr>
      <
tr>
        <
th align="right">身份证:</th>
        <
td><input name="idcard" type="text" class="input" id="idcard" /></td>
      </
tr>
      <
tr>
        <
th align="right">个人主页:</th>
        <
td><input name="homepage" type="text" class="input" id="homepage" /></td>
      </
tr>
      <
tr>
        <
th align="right">IP地址:</th>
        <
td><input name="ip" type="text" class="input" id="ip" /></td>
      </
tr>
      <
tr>
        <
th align="right">*加入日期:</th>
        <
td><input name="mdate" type="text" class="input" id="mdate" /></td>
      </
tr>
      <
tr>
        <
td height="30" colspan="2" align="center">
          <
input type="submit" value="提交表单" />&nbsp;&nbsp;&nbsp;
          <
input type="reset" value="重新填写" />
        </
td>
      </
tr>
    </
table>
  </
form>
</
body>
</
html> ;

[ 本帖最后由 aixle 于 2009-9-3 10:38 编辑 ]

附件

JS表单验证.rar (4.95 KB)

2009-9-3 10:38, 下载次数: 11

如履薄冰

好。。。。。。。。。。。。。。。。。。。。。。。。。。。。。