表单验证 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下载
示例:
代码如下:
[Ctrl+A 全选 提示:你可先修改部分代码,再点运行代码]
更新历史:
1.01
修正对12月份的日期验证(感谢flylg999)
1.03
修正Range验证类型时将数字当字符串比较的bug(感谢cncom和xtlhnhbb)
修正日期验证(感谢Papsam)
增加Username验证类型
增加对Phone验证类型时支持分机号
1.04
增加文件格式的过滤,用于上传时限制上传的文件格式
1.05
增强对身份证号码的验证
[ASP]版代码拷贝框
<%2
Class Validator3
'*************************************************4
' Validator for ASP beta 2 服务器端脚本5
' code by 我佛山人6
' wfsr@cunite.com7
' http://www.cunite.com8
'*************************************************9
Private Re, Dic10
Private Separator11
Private ErrorItem, ErrorMessage, ErrorMode, ErrorNo12
Private FormName, FormIndex, FilePath, GetMethod13

14
Private Sub Class_Initialize()15
Set Re = New RegExp16
Re.IgnoreCase = True17
Re.Global = True18
Set Dic = CreateObject("Scripting.Dictionary")19
Separator = ","20
ErrorItem = ""21
ErrorMessage = ""22
ErrorMode = 523
ErrorNo = 124
FilePath = Server.MapPath(Request.ServerVariables("Script_Name"))25
GetMethod = "FSO"26
End Sub27

28
Private Sub Class_Terminate()29
Set Re = Nothing30
Dic.RemoveAll()31
Set Dic = Nothing32
End Sub33

34
Public Sub Validate()35
IF Request("Submit")="" Then Exit Sub36
IF Not IsValidPost() Then Exit Sub37

38
With Dic39
.Add "Compare", "Compare( PostValue, operator, toObj)"40
.Add "Custom", "Custom( PostValue,regexp )"41
.Add "Date", "IsDateFormat( PostValue,format )"42
.Add "Limit", "Limit( PostValue,min, max )"43
.Add "LimitB", "LimitB( PostValue,min, max )"44
.Add "Range", "Range( PostValue,min, max )"45
.Add "Repeat", "IsEqual( PostValue, Request(toObj) )"46
.Add "Group", "Group( PostValue,min, max )"47

48
.Add "NotEqual", "Op1 <> Op2"49
.Add "GreaterThan", "Op1 > Op2"50
.Add "GreaterThanEqual", "Op1 >= Op2"51
.Add "LessThan", "Op1 < Op2"52
.Add "LessThanEqual", "Op1 <= Op2"53
.Add "Equal", "Op1 = Op2"54
End With55

56
Call MatchCode()57

58
IF ErrorMessage <> "" Then DisplayError59
End Sub60

61
Private Sub MatchCode()62
Dim bI, bG, bM63
Dim Str64

65
Select Case GetMethod66
Case "FSO" :67
Dim FSO : Set FSO = Server.CreateObject("Scripting.FileSystemObject")68
Set TS = FSO.OpenTextFile(FilePath, 1, false)69
Str = TS.ReadAll()70
TS.Close71
Set TS = Nothing72
Set FSO = Nothing73
Case "XMLHTTP" :74
Dim XHttp : Set XHttp = Server.CreateObject("MSXML2.XMLHTTP")75
With XHttp76
Call .Open("Get", "http://"&Request.ServerVariables("Server_Name")&Request.ServerVariables("Script_Name"), False)77
Call .Send()78
Str =B2S(.responseBody)79
End With80
Set XHttp = Nothing81
End Select82
Dim itemString83
With Re84
bI = .IgnoreCase85
bG = .Global86
bM = .MultiLine87
.IgnoreCase = True88
.Global = True89
.Pattern = "[\s\S]*<form [^>]+>([\s\S]+)<\/form>[\s\S]*"90
Str = .Replace(Str, "$1")91

92
.Global = True93
.MultiLine = True94
.Pattern = "<\/?(?!input|textarea|select)[^>]*>"95
Str = .Replace(Str, "")96

97
.Pattern = "^.*(<(?=input|textarea|select)[^>]*>).*$"98
Str = .Replace(Str, "$1")99

100
.Pattern = "([\r\n]+|^\s*)(?=<)"101
Str = .Replace(Str, "")102
While Test("dataType=([""\'])([^""\'>]+)\1", Str)103
.MultiLine = False104
.Pattern = "^([^\n]+)\n([\s\S]*)$"105
itemString = .Replace(Str, "$1")106
Str = .Replace(Str, "$2")107
.Pattern = "(name|dataType|to1|min|max|msg|require|regexp|format)=([""\'])([^""\'>]+)\2"108

109
Dim Matches : Set Matches = .Execute(itemString)110
Dim Match, RetStr : RetStr = ""111
For Each Match in Matches112
RetStr = RetStr & Match.Value & " : "113
Next114
Call IsValid(Replace(Replace(Replace(RetStr, " : $", ""), "to=", "toObj="), """Require""", """NotEmpty"""))115
Wend116
.IgnoreCase = bI117
.Global = bG118
.MultiLine = bM119

120
End With121
End Sub122

123
Private Sub IsValid(ByVal Str)124
Dim name, msg, dataType, toObj, min, max, require, regexp, format125
min = 1 : max = 100 : require = "true" : format = "YMD"126
Execute Str127
Dim PostValue : PostValue = Request(name)128
Dim Fun129
130
IF require = "false" AND PostValue = "" Then Exit Sub131

132
IF Dic.Exists(dataType) Then 133
Fun = Dic.Item(dataType) 134
Else Fun = "Is" & dataType &"( PostValue )"135
End IF136

137
IF Not Eval(Fun) Then Call AddError(name,msg)138
End Sub139

140
Private Sub DisplayError()141
ErrorItem = Replace(ErrorItem, "^(" & Separator & ")", "")142
ErrorMessage = Replace(ErrorMessage, "^(" & Separator & ")", "")143
Select Case ErrorMode144
Case 4 145
ErrorMessage = Join(Split(ErrorMessage, Separator), "</li><li>")146
Response.Clear147
Response.Write "<div style=""padding-left:100px;font:bold 12px Tahoma"">输入有错误:<br><ul><li>" & Replace(ErrorMessage, "\b\d+:", "") & "</li></ul>"148
Response.Write "<br><a href='javascript:history.back()'>返回重填</a></div>"149
Response.End150
Case Else151
Response.Write("<script defer>dispError(""" & ErrorItem & """, """ & ErrorMessage & """, " & ErrorMode & ", """ & Separator & """)</script>")152
End Select153
End Sub154

155
Public Function IsEmail(ByVal Str)156
IsEmail = Test("^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", Str)157
End Function158

159
Public Function IsUrl(ByVal Str)160
IsUrl = Test("^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>""])*$", Str)161
End Function162

163
Public Function IsNum(ByVal Str)164
IsNum= Test("^\d+$", Str)165
End Function166

167
Public Function IsQQ(ByVal Str)168
IsQQ = Test("^[1-9]\d{4,8}$", Str)169
End Function170

171
Public Function IsZip(ByVal Str)172
IsZip = Test("^[1-9]\d{5}$", Str)173
End Function174

175
Public Function IsIdCard(ByVal Str)176
IsIdCard = Test("^\d{15}(\d{2}[A-Za-z0-9])?$", Str)177
End Function178

179
Public Function IsChinese(ByVal Str)180
IsChinese = Test("^[\u0391-\uFFE5]+$", Str)181
End Function182

183
Public Function IsEnglish(ByVal Str)184
IsEnglish = Test("^[A-Za-z]+$", Str)185
End Function186

187
Public Function IsMobile(ByVal Str)188
IsMobile = Test("^((\(\d{3}\))|(\d{3}\-))?13\d{9}$", Str)189
End Function190

191
Public Function IsPhone(ByVal Str)192
IsPhone = Test("^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$", Str)193
End Function194

195
Public Function IsSafe(ByVal Str)196
IsSafe = (Test("^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\""]*)|.{0,5})$|\s", Str) = False)197
End Function198

199
Public Function IsNotEmpty(ByVal Str)200
IsNotEmpty = LenB(Str) > 0201
End Function202

203
Public Function IsDateFormat(ByVal Str, ByVal Format)204
IF Not IsDate(Str) Then205
IsDateFormat = False206
Exit Function207
End IF208

209
IF Format = "YMD" Then210
IsDateFormat = Test("^((\d{4})|(\d{2}))([-./])(\d{1,2})\4(\d{1,2})$", Str)211
Else 212
IsDateFormat = Test("^(\d{1,2})([-./])(\d{1,2})\\2((\d{4})|(\d{2}))$", Str)213
End IF214
End Function215

216
Public Function IsEqual(ByVal Src, ByVal Tar)217
IsEqual = (Src = Tar)218
End Function219

220
Public Function Compare(ByVal Op1, ByVal Operator, ByVal Op2)221
Compare = False222
IF Dic.Exists(Operator) Then223
Compare = Eval(Dic.Item(Operator))224
Elseif IsNotEmpty(Op1) Then225
Compare = Eval(Op1 & Operator & Op2 )226
End IF227
End Function228

229
Public Function Range(ByVal Src, ByVal Min, ByVal Max)230
Min = CInt(Min) : Max = CInt(Max)231
Range = (Min < Src And Src < Max)232
End Function233

234
Public Function Group(ByVal Src, ByVal Min, ByVal Max)235
Min = CInt(Min) : Max = CInt(Max)236
Dim Num : Num = UBound(Split(Src, ",")) + 1237
Group = Range(Num, Min - 1, Max + 1)238
End Function239

240
Public Function Custom(ByVal Str, ByVal Reg)241
Custom = Test(Reg, Str)242
End Function243

244
Public Function Limit(ByVal Str, ByVal Min, ByVal Max)245
Min = CInt(Min) : Max = CInt(Max)246
Dim L : L = Len(Str)247
Limit = (Min <= L And L <= Max)248
End Function249

250
Public Function LimitB(ByVal Str, ByVal Min, ByVal Max)251
Min = CInt(Min) : Max = CInt(Max)252
Dim L : L =bLen(Str)253
LimitB = (Min <= L And L <= Max)254
End Function255

256
Private Function Test(ByVal Pattern, ByVal Str)257
Re.Pattern = Pattern258
Test = Re.Test(Str)259
End Function260

261
Public Function bLen(ByVal Str)262
bLen = Len(Replace(Str, "[^\x00-\xFF]", ".."))263
End Function264

265
Private Function Replace(ByVal Str, ByVal Pattern, ByVal ReStr)266
Re.Pattern = Pattern267
Replace = Re.Replace(Str, ReStr)268
End Function269

270
Private Function B2S(ByVal iStr) 271
Dim reVal : reVal= ""272
Dim i, Code, nCode273
For i = 1 to LenB(iStr) 274
Code = AscB(MidB(iStr, i, 1)) 275
IF Code < &h80 Then 276
reVal = reVal & Chr(Code) 277
Else 278
nCode = AscB(MidB(iStr, i+1, 1)) 279
reVal = reVal & Chr(CLng(Code) * &h100 + CInt(nCode)) 280
i = i + 1 281
End IF 282
Next283
B2S = reVal 284
End Function285

286
Private Sub AddError(ByVal Name, ByVal Message)287
ErrorItem = ErrorItem & Separator & Name288
ErrorMessage = ErrorMessage & Separator & ErrorNo & ":" & Message289
ErrorNo = ErrorNo + 1290
End Sub291

292
Public Function IsValidPost()293
Dim Url1 : Url1 = Cstr(Request.ServerVariables("HTTP_REFERER"))294
Dim Url2 : Url2 = Cstr(Request.ServerVariables("SERVER_NAME"))295
IsValidPost = (Mid(Url1, 8, Len(Url2)) = Url2)296
End Function297

298
Public Property Let Mode(ByVal Val)299
ErrorMode = CInt(Val)300
End Property301

302
Public Property Let Form(ByVal Val)303
IF IsNumeric(Val) Then304
FormIndex = Val305
Else306
FormName = Val307
End IF308
End Property309

310
Public Property Let Path(ByVal Val)311
IF Test("^[A-Za-z]:\\\w+$", Val) Then312
FilePath = Val313
Else314
FilePath = Server.MapPath(Val)315
End IF316
End Property317

318
Public Property Let Method(ByVal Val)319
GetMethod = Val320
End Property321
End Class322
%>323
<title>表单验证类 Validator v1.0</title>324
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">325
<style>326
body,td{font:normal 12px Verdana;color:#333333}327
input,textarea,select,td{font:normal 12px Verdana;color:#333333;border:1px solid #999999;background:#ffffff}328
table{border-collapse:collapse;}329
td{padding:3px}330
input{height:20;}331
textarea{width:80%;height:50px;overfmin:auto;}332
form{display:inline}333
</style>334
<script>335
/*************************************************336
Validator for ASP beta 2 客户端脚本337
code by 我佛山人338
wfsr@cunite.com339
http://www.cunite.com340
*************************************************/341
function dispError(items, messages, mode, separator){342
var iArray = items.split(separator);343
for(var i=iArray.length-1;i>=0;i--)344
iArray[i] = getObj(iArray[i]);345
messages = ("以下原因导致提交失败:\t\t\t\t" + separator + messages).split(separator);346
switch(mode){347
case 2 :348
for(i=iArray.length-1;i>=0;i--)349
iArray[i].style.color = "red";350
case 1 :351
alert(messages.join("\n"));352
iArray[0].focus();353
break;354
case 3 :355
for(i=iArray.length-1;i>=0;i--){356
try{357
var span = document.createElement("SPAN");358
span.id = "__ErrorMessagePanel";359
span.style.color = "red";360
iArray[i].parentNode.appendChild(span);361
span.innerHTML = messages[i+1].replace(/\d+:/,"*");362
}363
catch(e){alert(e.description);}364
}365
iArray[0].focus();366
break;367
}368
}369

370
function getObj(name){371
var objs = document.getElementsByName(name);372
return objs[objs.length -1];373
}374
</script>375
<form name="theForm" id="demo" action="" method="post" onSubmit="return true">376
<table align="center">377
<tr>378
<td>真实姓名:</td><td><input name="Name" dataType="Chinese" msg="真实姓名只允许中文"></td>379
</tr>380
<tr>381
<td>英文名:</td><td><input name="Nick" dataType="English" require="false" msg="英文名只允许英文字母"></td>382
</tr>383
<tr>384
<td>主页:</td><td><input name="Homepage" require="false" dataType="Url" msg="非法的Url"></td>385
</tr>386
<tr>387
<td>密码:</td><td><input name="Password" dataType="Safe" msg="密码不符合安全规则" type="password"></td>388
</tr>389
<tr>390
<td>重复:</td><td><input name="Repeat" dataType="Repeat" to="Password" msg="两次输入的密码不一致" type="password"></td>391
</tr>392
<tr>393
<td>信箱:</td><td><input name="Email" dataType="Email" msg="信箱格式不正确"></td>394
</tr>395
<tr>396
<td>信箱:</td><td><input name="Email1" dataType="Repeat" to="Email" msg="两次输入的信箱不一致"></td>397
</tr>398
<tr>399
<td>QQ:</td><td><input name="QQ" require="false" dataType="QQ" msg="QQ号码不存在"></td>400
</tr>401
<tr>402
<td>身份证:</td><td><input name="Card" dataType="IdCard" msg="身份证号码不正确"></td>403
</tr>404
<tr>405
<td>年龄:</td><td><input name="Year" dataType="Range" msg="年龄必须在18~28之间" min="18" max="28"></td>406
</tr>407
<tr>408
<td>年龄1:</td><td><input name="Year1" require="false" dataType="Compare" msg="年龄必须在18以上" to1="18" operator="GreaterThanEqual"></td>409
</tr>410
<tr>411
<td>电话:</td><td><input name="Phone" require="false" dataType="Phone" msg="电话号码不正确"></td>412
</tr>413
<tr>414
<td>手机:</td><td><input name="Mobile" require="false" dataType="Mobile" msg="手机号码不正确"></td>415
</tr>416
<tr>417
<td>生日:</td><td><input name="Birthday" dataType="Date" format="YMD" msg="生日日期不存在"></td>418
</tr>419
<tr>420
<td>邮政编码:</td><td><input name="Zip" dataType="Custom" regexp="^[1-9]\d{5}$" msg="邮政编码不存在"></td>421
</tr>422
<tr>423
<td>邮政编码:</td><td><input name="Zip1" dataType="Zip" msg="邮政编码不存在"></td>424
</tr>425
<tr>426
<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
</tr>428
<tr>429
<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
</tr>431
<tr>432
<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
</tr>434
<tr>435
<td>自我介绍:</td><td><textarea name="Description" dataType="Limit" max="10" msg="自我介绍内容必须在10个字之内">中文是一个字</textarea></td>436
</tr>437
<tr>438
<td>自传:</td><td><textarea name="History" dataType="LimitB" min="3" max="10" msg="自传内容必须在[3~10]个字节之内">中文是两个字节t</textarea></td>439
</tr>440
<tr>441
<td colspan="2"><input name="Submit" type="submit" value="确定提交"></td>442
</tr>443
</table>444
</form>445
<%446
Dim V : Set V = New Validator447
V.Mode = 3448
V.Method = "XMLHTTP"449
V.Validate()450
Set V = Nothing451
%>452
</body>453
</html>
posted on 2005-06-11 12:13 ξσ Dicky σξ 阅读(878) 评论(1) 收藏 举报

浙公网安备 33010602011771号