表单验证 Validator v1.05

表单的验证一直是网页设计者头痛的问题,表单验证类 Validator就是为解决这个问题而写的,旨在使设计者从纷繁复杂的表单验证中解放出来,把精力集中于网页的设计和功能上的改进上。

Validator是基于JavaScript技术的伪静态类和对象的自定义属性,可以对网页中的表单项输入进行相应的验证,允许同一页面中同时验证多个表单,熟悉接口之后也可以对特定的表单项甚至仅仅是某个字符串进行验证。因为是伪静态类,所以在调用时不需要实例化,直接以"类名+.语法+属性或方法名"来调用。此外,Validator还提供3种不同的错误提示模式,以满足不同的需要。

Validator目前可实现的验证类型有:
[JavaScript] 版
Validator目前可实现的验证类型有:
1.是否为空;
2.中文字符;
3.双字节字符
4.英文;
5.数字;
6.整数;
7.实数;
8.Email地址;
9.使用HTTP协议的网址;
10.电话号码;
11.货币;
12.手机号码;
13.邮政编码;
14.身份证号码(1.05增强);
15.QQ号码;
16.日期;
17.符合安全规则的密码;
18.某项的重复值;
19.两数的关系比较;
20.判断输入值是否在(n, m)区间;
21.输入字符长度限制(可按字节比较);
22.对于具有相同名称的单选按钮的选中判断;
23.限制具有相同名称的多选按钮的选中数目;
24.自定义的正则表达式验证;
25.文件上传格式过滤(1.04)
运行环境(客户端):
在Windows Server 2003下用IE6.0+SP1和Mozilla Firefox 1.0测试通过;
在Lunix RedHat 9下的Netscape测试通过;

对于客户端的表单验证,这个基于JavaScript编写的Validator基本上都可以满足,具体可以下载CHM文件:Validator.CHM下载

示例:

代码如下:
<title>表单验证类 Validator v1.05</title> <style> body,td{font:normal 12px Verdana;color:#333333} input,textarea,select,td{font:normal 12px Verdana;color:#333333;border:1px solid #999999;background:#ffffff} table{border-collapse:collapse;} td{padding:3px} input{height:20;} textarea{width:80%;height:50px;overflow:auto;} form{display:inline} </style> <table align="center"> <form name="theForm" id="demo" method="get" onSubmit="return Validator.Validate(this,2)"> <tr> <td>身份证号:</td><td><input name="Card" dataType="IdCard" msg="身份证号错误"></td> </tr> <tr> <td>真实姓名:</td><td><input name="Name" dataType="Chinese" msg="真实姓名只允许中文"></td> </tr> <tr> <td>ID:</td><td><input name="username" dataType="Username" msg="ID名不符合规定"></td> </tr> <tr> <td>英文名:</td><td><input name="Nick" dataType="English" require="false" msg="英文名只允许英文字母"></td> </tr> <tr> <td>主页:</td><td><input name="Homepage" require="false" dataType="Url" msg="非法的Url"></td> </tr> <tr> <td>密码:</td><td><input name="Password" dataType="SafeString" msg="密码不符合安全规则" type="password"></td> </tr> <tr> <td>重复:</td><td><input name="Repeat" dataType="Repeat" to="Password" msg="两次输入的密码不一致" type="password"></td> </tr> <tr> <td>信箱:</td><td><input name="Email" dataType="Email" msg="信箱格式不正确"></td> </tr> <tr> <td>信箱:</td><td><input name="Email" dataType="Repeat" to="Email" msg="两次输入的信箱不一致"></td> </tr> <tr> <td>QQ:</td><td><input name="QQ" require="false" dataType="QQ" msg="QQ号码不存在"></td> </tr> <tr> <td>身份证:</td><td><input name="Card" dataType="IdCard" msg="身份证号码不正确"></td> </tr> <tr> <td>年龄:</td><td><input name="Year" dataType="Range" msg="年龄必须在18~28之间" min="18" max="28"></td> </tr> <tr> <td>年龄1:</td><td><input name="Year1" require="false" dataType="Compare" msg="年龄必须在18以上" to="18" operator="GreaterThanEqual"></td> </tr> <tr> <td>电话:</td><td><input name="Phone" require="false" dataType="Phone" msg="电话号码不正确"></td> </tr> <tr> <td>手机:</td><td><input name="Mobile" require="false" dataType="Mobile" msg="手机号码不正确"></td> </tr> <tr> <td>生日:</td><td><input name="Birthday" dataType="Date" format="ymd" msg="生日日期不存在"></td> </tr> <tr> <td>邮政编码:</td><td><input name="Zip" dataType="Custom" regexp="^[1-9]\d{5}$" msg="邮政编码不存在"></td> </tr> <tr> <td>邮政编码:</td><td><input name="Zip1" dataType="Zip" msg="邮政编码不存在"></td> </tr> <tr> <td>操作系统:</td><td><select name="Operation" dataType="Require" msg="未选择所用操作系统" ><option value="">选择您所用的操作系统</option><option value="Win98">Win98</option><option value="Win2k">Win2k</option><option value="WinXP">WinXP</option></select></td> </tr> <tr> <td>所在省份:</td><td>广东<input name="Province" value="1" type="radio">陕西<input name="Province" value="2" type="radio">浙江<input name="Province" value="3" type="radio">江西<input name="Province" value="4" type="radio" dataType="Group" msg="必须选定一个省份" ></td> </tr> <tr> <td>爱好:</td><td>运动<input name="Favorite" value="1" type="checkbox">上网<input name="Favorite" value="2" type="checkbox">听音乐<input name="Favorite" value="3" type="checkbox">看书<input name="Favorite" value="4" type="checkbox"" dataType="Group" min="2" max="3" msg="必须选择2~3种爱好"></td> </tr> <td>自我介绍:</td><td><textarea name="Description" dataType="Limit" max="10" msg="自我介绍内容必须在10个字之内">中文是一个字</textarea></td> </tr> <td>自传:</td><td><textarea name="History" dataType="LimitB" min="3" max="10" msg="自传内容必须在[3,10]个字节之内">中文是两个字节t</textarea></td> </tr> <tr> <td>相片上传:</td><td><input name="up" dataType="Filter" msg="非法的文件格式" type="file" accept="jpg, gif, png"></td> </tr> <tr> <td colspan="2"><input name="Submit" type="submit" value="确定提交"><input onClick="Validator.Validate(document.getElementById('demo'))" value="检验模式1" type="button"><input onClick="Validator.Validate(document.getElementById('demo'),2)" value="检验模式2" type="button"><input onClick="Validator.Validate(document.getElementById('demo'),3)" value="检验模式3" type="button"></td> </tr> </form> </table> <script> /************************************************* Validator v1.05 code by 我佛山人 wfsr@msn.com *************************************************/ Validator = { Require : /.+/, Email : /^\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}$/, Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/, IdCard : "this.IsIdCard(value)", Currency : /^\d+(\.\d+)?$/, Number : /^\d+$/, Zip : /^[1-9]\d{5}$/, QQ : /^[1-9]\d{4,8}$/, Integer : /^[-\+]?\d+$/, Double : /^[-\+]?\d+(\.\d+)?$/, English : /^[A-Za-z]+$/, Chinese : /^[\u0391-\uFFE5]+$/, Username : /^[a-z]\w{3,}$/i, UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/, IsSafe : function(str){return !this.UnSafe.test(str);}, SafeString : "this.IsSafe(value)", Filter : "this.DoFilter(value, getAttribute('accept'))", Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))", LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))", Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))", Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value", Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')", Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))", Custom : "this.Exec(value, getAttribute('regexp'))", Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))", ErrorItem : [document.forms[0]], ErrorMessage : ["以下原因导致提交失败:\t\t\t\t"], Validate : function(theForm, mode){ var obj = theForm || event.srcElement; var count = obj.elements.length; this.ErrorMessage.length = 1; this.ErrorItem.length = 1; this.ErrorItem[0] = obj; for(var i=0;i<count;i++){ with(obj.elements[i]){ var _dataType = getAttribute("dataType"); if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue; this.ClearState(obj.elements[i]); if(getAttribute("require") == "false" && value == "") continue; switch(_dataType){ case "IdCard" : case "Date" : case "Repeat" : case "Range" : case "Compare" : case "Custom" : case "Group" : case "Limit" : case "LimitB" : case "SafeString" : case "Filter" : if(!eval(this[_dataType])) { this.AddError(i, getAttribute("msg")); } break; default : if(!this[_dataType].test(value)){ this.AddError(i, getAttribute("msg")); } break; } } } if(this.ErrorMessage.length > 1){ mode = mode || 1; var errCount = this.ErrorItem.length; switch(mode){ case 2 : for(var i=1;i<errCount;i++) this.ErrorItem[i].style.color = "red"; case 1 : alert(this.ErrorMessage.join("\n")); this.ErrorItem[1].focus(); break; case 3 : for(var i=1;i<errCount;i++){ try{ var span = document.createElement("SPAN"); span.id = "__ErrorMessagePanel"; span.style.color = "red"; this.ErrorItem[i].parentNode.appendChild(span); span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*"); } catch(e){alert(e.description);} } this.ErrorItem[1].focus(); break; default : alert(this.ErrorMessage.join("\n")); break; } return false; } return true; }, limit : function(len,min, max){ min = min || 0; max = max || Number.MAX_VALUE; return min <= len && len <= max; }, LenB : function(str){ return str.replace(/[^\x00-\xff]/g,"**").length; }, ClearState : function(elem){ with(elem){ if(style.color == "red") style.color = ""; var lastNode = parentNode.childNodes[parentNode.childNodes.length-1]; if(lastNode.id == "__ErrorMessagePanel") parentNode.removeChild(lastNode); } }, AddError : function(index, str){ this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index]; this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str; }, Exec : function(op, reg){ return new RegExp(reg,"g").test(op); }, compare : function(op1,operator,op2){ switch (operator) { case "NotEqual": return (op1 != op2); case "GreaterThan": return (op1 > op2); case "GreaterThanEqual": return (op1 >= op2); case "LessThan": return (op1 < op2); case "LessThanEqual": return (op1 <= op2); default: return (op1 == op2); } }, MustChecked : function(name, min, max){ var groups = document.getElementsByName(name); var hasChecked = 0; min = min || 1; max = max || groups.length; for(var i=groups.length-1;i>=0;i--) if(groups[i].checked) hasChecked++; return min <= hasChecked && hasChecked <= max; }, DoFilter : function(input, filter){ return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g, filter.split(/\s*,\s*/).join("|")), "gi").test(input); }, IsIdCard : function(number){ var date, Ai; var verify = "10x98765432"; var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外']; var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i); if(re == null) return false; if(re[1] >= area.length || area[re[1]] == "") return false; if(re[2].length == 12){ Ai = number.substr(0, 17); date = [re[9], re[10], re[11]].join("-"); } else{ Ai = number.substr(0, 6) + "19" + number.substr(6); date = ["19" + re[4], re[5], re[6]].join("-"); } if(!this.IsDate(date, "ymd")) return false; var sum = 0; for(var i = 0;i<=16;i++){ sum += Ai.charAt(i) * Wi[i]; } Ai += verify.charAt(sum%11); return (number.length ==15 || number.length == 18 && number == Ai); }, IsDate : function(op, formatString){ formatString = formatString || "ymd"; var m, year, month, day; switch(formatString){ case "ymd" : m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$")); if(m == null ) return false; day = m[6]; month = m[5]*1; year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10)); break; case "dmy" : m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$")); if(m == null ) return false; day = m[1]; month = m[3]*1; year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10)); break; default : break; } if(!parseInt(month)) return false; month = month==0 ?12:month; var date = new Date(year, month-1, day); return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate()); function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;} } } </script>
[Ctrl+A 全选 提示:你可先修改部分代码,再点运行代码]

更新历史:

1.01
修正对12月份的日期验证(感谢flylg999)

1.03
修正Range验证类型时将数字当字符串比较的bug(感谢cncom和xtlhnhbb)
修正日期验证(感谢Papsam)
增加Username验证类型
增加对Phone验证类型时支持分机号

1.04
增加文件格式的过滤,用于上传时限制上传的文件格式

1.05
增强对身份证号码的验证

[ASP]版代码拷贝框

  1 None.gif < %
  2 None.gifClass Validator
  3 None.gif ' *************************************************
  4 None.gif'     Validator for ASP beta 2 服务器端脚本
  5 None.gif'     code by 我佛山人
  6 None.gif'     wfsr@cunite.com
  7 None.gif'     http://www.cunite.com
  8 None.gif' *************************************************
  9 None.gif      Private  Re, Dic
 10 None.gif     Private  Separator
 11 None.gif     Private  ErrorItem, ErrorMessage, ErrorMode, ErrorNo
 12 None.gif     Private  FormName, FormIndex, FilePath, GetMethod
 13 None.gif
 14 None.gif     Private   Sub  Class_Initialize()
 15 None.gif         Set  Re  =   New  RegExp
 16 None.gif        Re.IgnoreCase  =   True
 17 None.gif        Re.Global  =   True
 18 None.gif         Set  Dic  =   CreateObject ( " Scripting.Dictionary " )
 19 None.gif        Separator  =   " ,"
 20 None.gif         ErrorItem  =   " "
 21 None.gif         ErrorMessage  =   " "
 22 None.gif         ErrorMode  =   5
 23 None.gif        ErrorNo  =   1
 24 None.gif        FilePath  =  Server.MapPath(Request.ServerVariables( " Script_Name " ))
 25 None.gif        GetMethod  =   " FSO"
 26 None.gif      End Sub
 27 None.gif
 28 None.gif     Private   Sub  Class_Terminate()
 29 None.gif         Set  Re  =   Nothing
 30 None.gif        Dic.RemoveAll()
 31 None.gif         Set  Dic  =   Nothing
 32 None.gif     End Sub
 33 None.gif
 34 None.gif     Public   Sub  Validate()
 35 None.gif         IF  Request( " Submit " ) = ""   Then      Exit   Sub
 36 None.gif         IF   Not  IsValidPost()  Then      Exit   Sub
 37 None.gif
 38 None.gif         With  Dic
 39 None.gif            .Add  " Compare " " Compare( PostValue, operator, toObj)"
 40 None.gif             .Add  " Custom " " Custom( PostValue,regexp )"
 41 None.gif             .Add  " Date " " IsDateFormat( PostValue,format )"
 42 None.gif             .Add  " Limit " " Limit( PostValue,min, max )"
 43 None.gif             .Add  " LimitB " " LimitB( PostValue,min, max )"
 44 None.gif             .Add  " Range " " Range( PostValue,min, max )"
 45 None.gif             .Add  " Repeat " " IsEqual( PostValue, Request(toObj) )"
 46 None.gif             .Add  " Group " " Group( PostValue,min, max )"
 47 None.gif
 48 None.gif             .Add  " NotEqual " " Op1 <> Op2"
 49 None.gif             .Add  " GreaterThan " " Op1 > Op2"
 50 None.gif             .Add  " GreaterThanEqual " " Op1 >= Op2"
 51 None.gif             .Add  " LessThan " " Op1 < Op2"
 52 None.gif             .Add  " LessThanEqual " " Op1 <= Op2"
 53 None.gif             .Add  " Equal " " Op1 = Op2"
 54 None.gif          End   With
 55 None.gif
 56 None.gif         Call  MatchCode()
 57 None.gif
 58 None.gif         IF  ErrorMessage  <>   ""   Then  DisplayError
 59 None.gif     End Sub
 60 None.gif
 61 None.gif     Private   Sub  MatchCode()
 62 None.gif         Dim  bI, bG, bM
 63 None.gif         Dim  Str
 64 None.gif
 65 None.gif         Select   Case  GetMethod
 66 None.gif             Case   " FSO "  :
 67 None.gif                 Dim  FSO :  Set  FSO  =  Server. CreateObject ( " Scripting.FileSystemObject " )
 68 None.gif                 Set  TS  =  FSO.OpenTextFile(FilePath,  1 false )
 69 None.gif                Str  =  TS.ReadAll()
 70 None.gif                TS.Close
 71 None.gif                 Set  TS  =   Nothing
 72 None.gif                 Set  FSO  =   Nothing
 73 None.gif             Case   " XMLHTTP "  :
 74 None.gif                 Dim  XHttp :  Set  XHttp  =  Server. CreateObject ( " MSXML2.XMLHTTP " )
 75 None.gif                 With  XHttp
 76 None.gif                     Call  .Open( " Get " " http:// " & Request.ServerVariables( " Server_Name " ) & Request.ServerVariables( " Script_Name " ),  False )
 77 None.gif                     Call  .Send()
 78 None.gif                    Str  = B2S(.responseBody)
 79 None.gif                 End   With
 80 None.gif                 Set  XHttp  =   Nothing
 81 None.gif         End   Select
 82 None.gif         Dim  itemString
 83 None.gif         With  Re
 84 None.gif            bI  =  .IgnoreCase
 85 None.gif            bG  =  .Global
 86 None.gif            bM  =  .MultiLine
 87 None.gif            .IgnoreCase  =   True
 88 None.gif            .Global  =   True
 89 None.gif            .Pattern  =   " [\s\S]*<form [^>]+>([\s\S]+)<\/form>[\s\S]*"
 90 None.gif             Str  =  . Replace (Str,  " $1 " )
 91 None.gif
 92 None.gif            .Global  =   True
 93 None.gif            .MultiLine  =   True
 94 None.gif            .Pattern  =   " <\/?(?!input|textarea|select)[^>]*>"
 95 None.gif             Str  =  . Replace (Str,  "" )
 96 None.gif
 97 None.gif            .Pattern  =   " ^.*(<(?=input|textarea|select)[^>]*>).*$"
 98 None.gif             Str  =  . Replace (Str,  " $1 " )
 99 None.gif
100 None.gif            .Pattern  =   " ([\r\n]+|^\s*)(?=<)"
101 None.gif             Str  =  . Replace (Str,  "" )
102 None.gif             While  Test( " dataType=([""\'])([^""\'>]+)\1 " , Str)
103 None.gif                .MultiLine  =   False
104 None.gif                .Pattern  =   " ^([^\n]+)\n([\s\S]*)$"
105 None.gif                 itemString  =  . Replace (Str,  " $1 " )
106 None.gif                Str  =  . Replace (Str,  " $2 " )
107 None.gif                .Pattern  =   " (name|dataType|to1|min|max|msg|require|regexp|format)=([""\'])([^""\'>]+)\2"
108 None.gif
109 None.gif                  Dim  Matches :  Set  Matches  =  . Execute (itemString)
110 None.gif                 Dim  Match, RetStr : RetStr  =   " "
111 None.gif                     For   Each  Match in Matches
112 None.gif                      RetStr  =  RetStr  &  Match.Value  &   "  : "
113 None.gif                     Next
114 None.gif                 Call  IsValid( Replace ( Replace ( Replace (RetStr,  "  : $ " "" ),  " to= " " toObj= " ),  " ""Require"" " " ""NotEmpty"" " ))
115 None.gif             Wend
116 None.gif            .IgnoreCase  =  bI
117 None.gif            .Global  =  bG
118 None.gif            .MultiLine  =  bM
119 None.gif
120 None.gif         End   With
121 None.gif     End Sub
122 None.gif
123 None.gif     Private   Sub  IsValid(ByVal Str)
124 None.gif         Dim  name, msg, dataType, toObj, min, max, require, regexp, format
125 None.gif        min  =   1  : max  =   100  : require  =   " true "  : format  =   " YMD"
126 None.gif          Execute  Str
127 None.gif         Dim  PostValue : PostValue  =  Request(name)
128 None.gif         Dim  Fun
129 None.gif        
130 None.gif         IF  require  =   " false "   AND  PostValue  =   ""   Then   Exit   Sub
131 None.gif
132 None.gif         IF  Dic.Exists(dataType)  Then     
133 None.gif            Fun  =  Dic.Item(dataType) 
134 None.gif         Else  Fun  =   " Is "   &  dataType  & " ( PostValue )"
135 None.gif          End   IF
136 None.gif
137 None.gif         IF   Not   Eval (Fun)  Then   Call  AddError(name,msg)
138 None.gif     End Sub
139 None.gif
140 None.gif     Private   Sub  DisplayError()
141 None.gif        ErrorItem  =   Replace (ErrorItem,  " ^( "   &  Separator  &   " ) " "" )
142 None.gif        ErrorMessage  =   Replace (ErrorMessage,  " ^( "   &  Separator  &   " ) " "" )
143 None.gif         Select   Case  ErrorMode
144 None.gif             Case   4  
145 None.gif                ErrorMessage  =   Join ( Split (ErrorMessage, Separator),  " </li><li> " )
146 None.gif                Response.Clear
147 None.gif                Response.Write  " <div style=""padding-left:100px;font:bold 12px Tahoma"">输入有错误:<br><ul><li> "   &   Replace (ErrorMessage,  " \b\d+: " "" &   " </li></ul>"
148 None.gif                 Response.Write  " <br><a href='javascript:history.back()'>返回重填</a></div>"
149 None.gif                 Response. End
150 None.gif             Case   Else
151 None.gif                Response.Write( " <script defer>dispError("" "   &  ErrorItem  &   " "", "" "   &  ErrorMessage  &   " "",  "   &  ErrorMode  &   " , "" "   &  Separator  &   " "")</script> " )
152 None.gif         End   Select
153 None.gif     End Sub
154 None.gif
155 None.gif     Public   Function  IsEmail(ByVal Str)
156 None.gif        IsEmail  =  Test( " ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ " , Str)
157 None.gif     End Function
158 None.gif
159 None.gif     Public   Function  IsUrl(ByVal Str)
160 None.gif        IsUrl  =  Test( " ^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>""])*$ " , Str)
161 None.gif     End Function
162 None.gif
163 None.gif     Public   Function  IsNum(ByVal Str)
164 None.gif        IsNum =  Test( " ^\d+$ " , Str)
165 None.gif     End Function
166 None.gif
167 None.gif     Public   Function  IsQQ(ByVal Str)
168 None.gif        IsQQ  =  Test( " ^[1-9]\d{4,8}$ " , Str)
169 None.gif     End Function
170 None.gif
171 None.gif     Public   Function  IsZip(ByVal Str)
172 None.gif        IsZip  =  Test( " ^[1-9]\d{5}$ " , Str)
173 None.gif     End Function
174 None.gif
175 None.gif     Public   Function  IsIdCard(ByVal Str)
176 None.gif        IsIdCard  =  Test( " ^\d{15}(\d{2}[A-Za-z0-9])?$ " , Str)
177 None.gif     End Function
178 None.gif
179 None.gif     Public   Function  IsChinese(ByVal Str)
180 None.gif        IsChinese  =  Test( " ^[\u0391-\uFFE5]+$ " , Str)
181 None.gif     End Function
182 None.gif
183 None.gif     Public   Function  IsEnglish(ByVal Str)
184 None.gif        IsEnglish  =  Test( " ^[A-Za-z]+$ " , Str)
185 None.gif     End Function
186 None.gif
187 None.gif     Public   Function  IsMobile(ByVal Str)
188 None.gif        IsMobile  =  Test( " ^((\(\d{3}\))|(\d{3}\-))?13\d{9}$ " , Str)
189 None.gif     End Function
190 None.gif
191 None.gif     Public   Function  IsPhone(ByVal Str)
192 None.gif        IsPhone  =  Test( " ^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$ " , Str)
193 None.gif     End Function
194 None.gif
195 None.gif     Public   Function  IsSafe(ByVal Str)
196 None.gif        IsSafe  =  (Test( " ^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\""]*)|.{0,5})$|\s " , Str)  =   False )
197 None.gif     End Function
198 None.gif
199 None.gif     Public   Function  IsNotEmpty(ByVal Str)
200 None.gif        IsNotEmpty  =  LenB(Str)  >   0
201 None.gif     End Function
202 None.gif
203 None.gif     Public   Function  IsDateFormat(ByVal Str, ByVal Format)
204 None.gif         IF   Not   IsDate (Str)  Then
205 None.gif            IsDateFormat  =   False
206 None.gif             Exit   Function
207 None.gif         End   IF
208 None.gif
209 None.gif         IF  Format  =   " YMD "   Then
210 None.gif            IsDateFormat  =  Test( " ^((\d{4})|(\d{2}))([-./])(\d{1,2})\4(\d{1,2})$ " , Str)
211 None.gif         Else  
212 None.gif            IsDateFormat  =  Test( " ^(\d{1,2})([-./])(\d{1,2})\\2((\d{4})|(\d{2}))$ " , Str)
213 None.gif         End   IF
214 None.gif     End Function
215 None.gif
216 None.gif     Public   Function  IsEqual(ByVal Src, ByVal Tar)
217 None.gif        IsEqual  =  (Src  =  Tar)
218 None.gif     End Function
219 None.gif
220 None.gif     Public   Function  Compare(ByVal Op1, ByVal Operator, ByVal Op2)
221 None.gif        Compare  =   False
222 None.gif         IF  Dic.Exists(Operator)  Then
223 None.gif            Compare  =   Eval (Dic.Item(Operator))
224 None.gif             Elseif  IsNotEmpty(Op1)  Then
225 None.gif                Compare  =   Eval (Op1  &   Operator  &  Op2 )
226 None.gif         End   IF
227 None.gif     End Function
228 None.gif
229 None.gif     Public   Function  Range(ByVal Src, ByVal Min, ByVal Max)
230 None.gif        Min  =   CInt (Min) : Max  =   CInt (Max)
231 None.gif        Range  =  (Min  <  Src  And  Src  <  Max)
232 None.gif     End Function
233 None.gif
234 None.gif     Public   Function  Group(ByVal Src, ByVal Min, ByVal Max)
235 None.gif        Min  =   CInt (Min) : Max  =   CInt (Max)
236 None.gif         Dim  Num : Num  =   UBound ( Split (Src,  " , " ))  +   1
237 None.gif        Group  =  Range(Num, Min  -   1 , Max  +   1 )
238 None.gif     End Function
239 None.gif
240 None.gif     Public   Function  Custom(ByVal Str, ByVal Reg)
241 None.gif        Custom  =  Test(Reg, Str)
242 None.gif     End Function
243 None.gif
244 None.gif     Public   Function  Limit(ByVal Str, ByVal Min, ByVal Max)
245 None.gif        Min  =   CInt (Min) : Max  =   CInt (Max)
246 None.gif         Dim  L : L  =   Len (Str)
247 None.gif        Limit  =  (Min  <=  L  And  L  <=  Max)
248 None.gif     End Function
249 None.gif
250 None.gif     Public   Function  LimitB(ByVal Str, ByVal Min, ByVal Max)
251 None.gif        Min  =   CInt (Min) : Max  =   CInt (Max)
252 None.gif         Dim  L : L  = bLen(Str)
253 None.gif        LimitB  =  (Min  <=  L  And  L  <=  Max)
254 None.gif     End Function
255 None.gif
256 None.gif     Private   Function  Test(ByVal Pattern, ByVal Str)
257 None.gif        Re.Pattern  =  Pattern
258 None.gif        Test  =  Re.Test(Str)
259 None.gif     End Function
260 None.gif
261 None.gif     Public   Function  bLen(ByVal Str)
262 None.gif        bLen  =   Len ( Replace (Str,  " [^\x00-\xFF] " " .. " ))
263 None.gif     End Function
264 None.gif
265 None.gif     Private   Function   Replace (ByVal Str, ByVal Pattern, ByVal ReStr)
266 None.gif        Re.Pattern  =  Pattern
267 None.gif         Replace   =      Re. Replace (Str, ReStr)
268 None.gif     End Function
269 None.gif
270 None.gif     Private   Function  B2S(ByVal iStr) 
271 None.gif         Dim  reVal : reVal =   " "
272 None.gif          Dim  i, Code, nCode
273 None.gif         For  i  =   1   to  LenB(iStr) 
274 None.gif            Code  =  AscB(MidB(iStr, i,  1 )) 
275 None.gif             IF  Code  <   & h80  Then  
276 None.gif                reVal  =  reVal  &   Chr (Code) 
277 None.gif             Else  
278 None.gif                nCode  =  AscB(MidB(iStr, i + 1 1 )) 
279 None.gif                reVal  =  reVal  &   Chr ( CLng (Code)  *   & h100  +   CInt (nCode)) 
280 None.gif                i  =  i  +   1  
281 None.gif             End   IF  
282 None.gif         Next
283 None.gif        B2S  =  reVal 
284 None.gif     End Function
285 None.gif
286 None.gif     Private   Sub  AddError(ByVal Name, ByVal Message)
287 None.gif        ErrorItem  =  ErrorItem  &  Separator  &  Name
288 None.gif        ErrorMessage  =  ErrorMessage  &  Separator  &  ErrorNo  &   " : "   &  Message
289 None.gif        ErrorNo  =  ErrorNo  +   1
290 None.gif     End Sub
291 None.gif
292 None.gif     Public   Function  IsValidPost()
293 None.gif         Dim  Url1 : Url1  =   Cstr (Request.ServerVariables( " HTTP_REFERER " ))
294 None.gif         Dim  Url2 : Url2  =   Cstr (Request.ServerVariables( " SERVER_NAME " ))
295 None.gif        IsValidPost  =  ( Mid (Url1,  8 Len (Url2))  =  Url2)
296 None.gif     End Function
297 None.gif
298 None.gif     Public   Property   Let  Mode(ByVal Val)
299 None.gif        ErrorMode  =   CInt (Val)
300 None.gif     End Property
301 None.gif
302 None.gif     Public   Property   Let  Form(ByVal Val)
303 None.gif         IF   IsNumeric (Val)  Then
304 None.gif            FormIndex  =  Val
305 None.gif         Else
306 None.gif            FormName  =  Val
307 None.gif         End   IF
308 None.gif     End Property
309 None.gif
310 None.gif     Public   Property   Let  Path(ByVal Val)
311 None.gif         IF  Test( " ^[A-Za-z]:\\\w+$ " , Val)  Then
312 None.gif            FilePath  =  Val
313 None.gif         Else
314 None.gif            FilePath  =  Server.MapPath(Val)
315 None.gif         End   IF
316 None.gif     End Property
317 None.gif
318 None.gif     Public   Property   Let  Method(ByVal Val)
319 None.gif        GetMethod  =  Val
320 None.gif     End Property
321 None.gif End  Class
322 None.gif% >
323 None.gif  < title > 表单验证类 Validator v1. 0 </ title >
324 None.gif  < meta http - equiv = " Content-Type "  content = " text/html; charset=gb2312 " >
325 None.gif  < style >
326 None.gif body,td{font:normal 12px Verdana;color:# 333333 }
327 None.gif input,textarea, select ,td{font:normal 12px Verdana;color:# 333333 ;border:1px solid # 999999 ;background:#ffffff}
328 None.gif table{border - collapse:collapse;}
329 None.gif td{padding:3px}
330 None.gif input{height: 20 ;}
331 None.gif textarea{width: 80 %;height:50px;overfmin:auto;}
332 None.gif form{display:inline}
333 None.gif  </ style >
334 None.gif  < script >
335 None.gif  /*************************************************
336 None.gif    Validator  for  ASP beta  2  客户端脚本
337 None.gif    code by 我佛山人
338 None.gif    wfsr@cunite.com
339 None.gif    http: // www.cunite.com
340 None.gif *************************************************/
341 None.gif  function  dispError(items, messages, mode, separator){
342 None.gif    var iArray  =  items. split (separator);
343 None.gif     for (var i = iArray.length - 1 ;i >= 0 ;i -- )
344 None.gif        iArray[i]  =  getObj(iArray[i]);
345 None.gif    messages  =  ( " 以下原因导致提交失败:\t\t\t\t "   +  separator  +  messages). split (separator);
346 None.gif    switch(mode){
347 None.gif         case   2  :
348 None.gif             for (i = iArray.length - 1 ;i >= 0 ;i -- )
349 None.gif                iArray[i].style.color  =   " red " ;
350 None.gif         case   1  :
351 None.gif            alert(messages. join ( " \n " ));
352 None.gif            iArray[ 0 ].focus();
353 None.gif            break;
354 None.gif         case   3  :
355 None.gif             for (i = iArray.length - 1 ;i >= 0 ;i -- ){
356 None.gif                try{
357 None.gif                    var span  =  document.createElement( " SPAN " );
358 None.gif                    span.id  =   " __ErrorMessagePanel " ;
359 None.gif                    span.style.color  =   " red " ;
360 None.gif                    iArray[i].parentNode.appendChild(span);
361 None.gif                    span.innerHTML  =  messages[i + 1 ]. replace ( /\ d + : / , " * " );
362 None.gif                }
363 None.gif                catch(e){alert(e.description);}
364 None.gif            }
365 None.gif            iArray[ 0 ].focus();
366 None.gif            break;
367 None.gif    }
368 None.gif }
369 None.gif
370 None.gif  function  getObj(name){
371 None.gif    var objs  =  document.getElementsByName(name);
372 None.gif    return objs[objs.length  - 1 ];
373 None.gif }
374 None.gif </ script >
375 None.gif  < form name = " theForm "  id = " demo "  action = ""  method = " post "  onSubmit = " return true " >
376 None.gif  < table align = " center " >
377 None.gif     < tr >
378 None.gif    < td > 真实姓名: </ td >< td >< input name = " Name "  dataType = " Chinese "  msg = " 真实姓名只允许中文 " ></ td >
379 None.gif   </ tr >
380 None.gif   < tr >
381 None.gif    < td > 英文名: </ td >< td >< input name = " Nick "  dataType = " English "  require = " false "  msg = " 英文名只允许英文字母 " ></ td >
382 None.gif   </ tr >
383 None.gif     < tr >
384 None.gif    < td > 主页: </ td >< td >< input name = " Homepage "  require = " false "  dataType = " Url "    msg = " 非法的Url " ></ td >
385 None.gif   </ tr >
386 None.gif   < tr >
387 None.gif    < td > 密码: </ td >< td >< input name = " Password "  dataType = " Safe "    msg = " 密码不符合安全规则 "  type = " password " ></ td >
388 None.gif   </ tr >
389 None.gif   < tr >
390 None.gif    < td > 重复: </ td >< td >< input name = " Repeat "  dataType = " Repeat "   to = " Password "  msg = " 两次输入的密码不一致 "  type = " password " ></ td >
391 None.gif   </ tr >
392 None.gif   < tr >
393 None.gif    < td > 信箱: </ td >< td >< input name = " Email "  dataType = " Email "  msg = " 信箱格式不正确 " ></ td >
394 None.gif   </ tr >
395 None.gif     < tr >
396 None.gif    < td > 信箱: </ td >< td >< input name = " Email1 "  dataType = " Repeat "   to = " Email "  msg = " 两次输入的信箱不一致 " ></ td >
397 None.gif   </ tr >
398 None.gif   < tr >
399 None.gif    < td > QQ: </ td >< td >< input name = " QQ "  require = " false "  dataType = " QQ "  msg = " QQ号码不存在 " ></ td >
400 None.gif   </ tr >
401 None.gif     < tr >
402 None.gif    < td > 身份证: </ td >< td >< input name = " Card "  dataType = " IdCard "  msg = " 身份证号码不正确 " ></ td >
403 None.gif   </ tr >
404 None.gif   < tr >
405 None.gif    < td > 年龄: </ td >< td >< input name = " Year "  dataType = " Range "  msg = " 年龄必须在18~28之间 "  min = " 18 "  max = " 28 " ></ td >
406 None.gif   </ tr >
407 None.gif    < tr >
408 None.gif    < td > 年龄1: </ td >< td >< input name = " Year1 "  require = " false "  dataType = " Compare "  msg = " 年龄必须在18以上 "  to1 = " 18 "  operator = " GreaterThanEqual " ></ td >
409 None.gif   </ tr >
410 None.gif    < tr >
411 None.gif    < td > 电话: </ td >< td >< input name = " Phone "  require = " false "  dataType = " Phone "  msg = " 电话号码不正确 " ></ td >
412 None.gif   </ tr >
413 None.gif    < tr >
414 None.gif    < td > 手机: </ td >< td >< input name = " Mobile "  require = " false "  dataType = " Mobile "  msg = " 手机号码不正确 " ></ td >
415 None.gif   </ tr >
416 None.gif      < tr >
417 None.gif    < td > 生日: </ td >< td >< input name = " Birthday "  dataType = " Date "  format = " YMD "  msg = " 生日日期不存在 " ></ td >
418 None.gif   </ tr >
419 None.gif    < tr >
420 None.gif    < td > 邮政编码: </ td >< td >< input name = " Zip "  dataType = " Custom "  regexp = " ^[1-9]\d{5}$ "  msg = " 邮政编码不存在 " ></ td >
421 None.gif   </ tr >
422 None.gif   < tr >
423 None.gif    < td > 邮政编码: </ td >< td >< input name = " Zip1 "  dataType = " Zip "  msg = " 邮政编码不存在 " ></ td >
424 None.gif   </ tr >
425 None.gif   < tr >
426 None.gif    < td > 操作系统: </ td >< td >< select  name = " OS "  dataType = " Require "   msg = " 未选择所用操作系统 "   >< option  value = "" > 选择您所用的操作系统 </ option >< option  value = " Win98 " > Win98 </ option >< option  value = " Win2k " > Win2k </ option >< option  value = " WinXP " > WinXP </ option ></ select ></ td >
427 None.gif   </ tr >
428 None.gif   < tr >
429 None.gif    < td > 所在省份: </ td >< td > 广东 < input name = " Province "  value = " 1 "  type = " radio " > 陕西 < input name = " Province "  value = " 2 "  type = " radio " > 浙江 < input name = " Province "  value = " 3 "  type = " radio " > 江西 < input name = " Province "  value = " 4 "  type = " radio "  dataType = " Group "   msg = " 必须选定一个省份 " ></ td >
430 None.gif   </ tr >
431 None.gif   < tr >
432 None.gif    < td > 爱好: </ td >< td > 运动 < input name = " Favorite "  value = " 1 "  type = " checkbox " > 上网 < input name = " Favorite "  value = " 2 "  type = " checkbox " > 听音乐 < input name = " Favorite "  value = " 3 "  type = " checkbox " > 看书 < input name = " Favorite "  value = " 4 "  type = " checkbox "  dataType = " Group "  min = " 2 "  max = " 3 "   msg = " 必须选择2~3种爱好 " ></ td >
433 None.gif   </ tr >
434 None.gif   < tr >
435 None.gif    < td > 自我介绍: </ td >< td >< textarea name = " Description "  dataType = " Limit "  max = " 10 "   msg = " 自我介绍内容必须在10个字之内 " > 中文是一个字 </ textarea ></ td >
436 None.gif   </ tr >
437 None.gif   < tr >
438 None.gif      < td > 自传: </ td >< td >< textarea name = " History "  dataType = " LimitB "  min = " 3 "  max = " 10 "   msg = " 自传内容必须在[3~10]个字节之内 " > 中文是两个字节t </ textarea ></ td >
439 None.gif   </ tr >
440 None.gif   < tr >
441 None.gif    < td colspan = " 2 " >< input name = " Submit "  type = " submit "  value = " 确定提交 " ></ td >
442 None.gif   </ tr >
443 None.gif  </ table >
444 None.gif </ form >
445 None.gif < %
446 None.gif     Dim  V :  Set  V  =   New  Validator
447 None.gif    V.Mode  =   3
448 None.gif    V.Method  =   " XMLHTTP"
449 None.gif     V.Validate()
450 None.gif     Set  V  =   Nothing
451 None.gif% >
452 None.gif </ body >
453 None.gif </ html >


 

转载于:https://www.cnblogs.com/Dicky/archive/2005/06/11/172491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值