通用验证脚本
表单通用验证脚本,
例如:
....
1

/**//****************************************2
* Create by Oceanchip 2008-3-313
***************************************/4
5

/**//*****************************6
* namespace:System7
******************************/ 8
if(!window.System)9

window.System =
{};10
11

/**//************************************12
* function System.createDeletegate13
************************************/14
System.createDeletegate=function(instance,method)15


{16
///<summary> Creates a delegate function that executes the specified method in the correct context.</summary>17
///<param name="instance">The instance whose method should be executed.</param>18
///<param name="method">The method to execute.</param>19
///<returns>The delegate function.</returns>20
return function()21

{22
return method.apply(instance,arguments);23
}24
}25

/**//************************************26
* function System.merge27
************************************/28
System.merge = function(destination,source,preventNew)29

{30
///<summary>Merges properties from a source object into a destination object.</summary>31
///<param name="destination">The destination object.</param>32
///<param name="source">The source object.</param>33
///<param name="preventNew">Indicates whether or not new properties are prevented from being added to the destination object.</param>34
35
var root = destination;36
for( var i in source)37

{38
var s = source[i],d;39
var properties = i.split(".");40
var count = properties.length;41
42
for(var j = 0; j < count; j++)43

{44
i =properties[j];45
d = destination[i];46
if(d)47

{48
if(typeof d == "object")49
destination = d;50
}51
else if (j > 0 && j < count -1)52

{53

var obj =
{};54
obj[properties.slice(j,count).join(".")]=s;55
s = obj;56
break;57
}58
}59
60
if(d && typeof(d) == "object" && typeof(s) == "object")61

{62
this.merge(d,s,false);63
}64
else if (preventNew && count<=1 && typeof(d) == "undefined")65
throw new Error("Undefined property:"+i);66
else67
destination[i] = s;68
69
destination = root;70
}71
}72

/**//************************************73
* function System.extend74
************************************/75
System.extend = function(baseClass,derivedClass,deriveMembers)76

{77
///<summary>Provides support for class inheritance.</summary>78
///<param name="baseClass">The base class.</param>79
///<param name="derivedClass">The derived class.</param>80
///<param name="derivedMembers">The members to add to the derived class and override in the base class.</param>81
82

var F = function()
{};83
F.prototype = baseClass.prototype;84
derivedClass.prototype = new F();85
derivedClass.prototype.constructor = derivedClass;86
derivedClass.base = baseClass.prototype;87
88
if(baseClass.prototype.constructor == Object.prototype.constructor)89
baseClass.prototype.constructor = baseClass;90
91
//Note:IE will not enumerate derived members that exist in the Object92
//prototype(e.g. toString,valueOf). If overriding these members93
//is necessary,search for "_IEEnumFix" for one possible solution. 94
if(deriveMembers)95

{96
for(var i in deriveMembers)97
derivedClass.prototype[i] = deriveMembers[i];98
}99
}100
101

/**//************************************102
* function System.parseBoolean103
************************************/104
System.parseBoolean = function(value)105

{106
///<summary>Parse a boolean from the specified value.</summary>107
///<param name="value">The value to parse.</param>108
///<returns>True if the specified value is parsed as true.</returns>109
110
return (typeof(value)=="string") ? (value.toLowerCase() == "true"):Boolean(value);111
}112
113

/**//************************************114
* function System.formatString115
************************************/116
System.formatString = function(value)117

{118
///<summary>FOrmats a string.</summary>119
///<param name = "value">The string to format.</param>120
///<returns>The formatted string.</returns>121
122
for(var i = 1,j = arguments.length;i<j; i++)123

{124
value = value.replace("{"+ (i - 1) + "}",arguments[i]);125
}126
return value;127
}128
System.trim = function(value)129

{130
return value.replace(/(^\s*)|(\s*$)/g, "");131
}132

/**//*************************************133
* function System.getUniqueId134
************************************/135
System.getUniqueId = function(prefix)136

{137
///<summary>Get a random unique identifer.</summary>138
///<param name="prefix">The prefix to prepend to the generated identifier.</param>139
///<returns> The unique identifier.</returns>140
141
return prefix + Math.random().toString().substring(2);142
}143
144

/**//************************************145
* function System.Object146
************************************/147
System.Object = function()148

{149
///<summary>Provides a common base class with support for options and events.</summary>150
151

this.options =
{};152

this.eventHandlers =
{};153
}154
155
System.Object.prototype = 156

{157
setOptions: function(options)158

{159
///<summary>Merges the specified options with existing options.</summary>160
///<param name="options">The options to merge.</summary>161
162
System.merge(this.options,options,true);163
},164
165
addEventListener : function(name , handler)166

{167
///<summary>Adds an event handler to the list of handlers to be called when the specified event is fired.</summary>168
///<param name="name">The event name.</param>169
///<param name="handler">The event handler to add.</param>170
///<returns>The identifying token(i.e. index) for the added event handler.</returns>171
172
var handlers = this.eventHandlers[name];173
174
if(!handlers)175
this.eventHandlers[name] = handlers = [];176
177
var token = handlers.length;178
handlers[token] = handler;179
return token;180
},181
182
removeEventListener: function(name,handlerOrToken)183

{184
///<summary>Removes the first matching event handler from the list of handlers to be called when the specified event is fired.</summary>185
///<param name="name">The event name.</param>186
///<param name="handlerOrToken">The event handler or indentiing token to remove.</param>187
188
if(typeof(handlerOrToken) == "function")189

{190
var handlers = this.eventHandlers[name];191
192
if(handlers)193

{194
for(var i = 0, j = handlers.length; i < j; i++)195

{196
if(handlers[i] == handlerOrToken)197
break;198
}199
200
handlers.splice(i,1);201
}202
}203
},204
205
fireEvent: function(name, e)206

{207
///<summary> Fires the specified event and calls each listening handler.</summary>208
///<param name="name">The name of the event to fire.</param>209
///<param name="e">The event arguments to pass to each handler.</param>210
211
var handlers = this.eventHandlers[name];212
213
if(handlers)214
for( var i = 0, j = handlers.length; i < j; i++)215
handlers[i](this,e);216
},217
218
dispose: function()219

{220
///<summary> Release the object from memory.</summary>221
222
this.options = null;223
this.eventHandlers = null;224
}225
}226

/**//************************************227
* function System.Validate228
************************************/229
System.Validate = function(options)230


{231
///<summary>Provider support from Validate check</summary>232
///<param name="options">The options from Validate.</param>233
234
System.Validate.base.constructor.call(this);235
236
this.reg = null;237
this.msg = '';238
239
}240
System.extend(System.Object,System.Validate,241


{242
check:function(val)243

{244
if(this.reg.test(val))245
return true;246
return false;247
},248
regex:function(val,reg)249

{250
if(reg.test(val))251

{252
this.msg = "";253
return true;254
}255
return false;256
},257
//是否数字258
isInteger:function(val)259

{260
if(System.trim(val) == '')return true;261
this.reg = /^[-+]?\d*$/;262
this.msg='请输入阿拉伯数字\r\n'; 263
return this.check(val);264
},265
//是否浮点数266
isDouble:function(val)267

{268
if(System.trim(val) == '')return true;269
this.reg =/^[-+]?\d+(\.\d+)?$/;270
this.msg='请输入数字,如3.14\r\n';271
return this.check(val);272
},273
//电子邮件274
isEmail:function(val)275

{276
if(System.trim(val) == '')return true;277
this.reg = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;278
this.msg ="请输入合法的email地址\r\n";279
return this.check(val);280
},281
//货币282
isCurrency:function(val)283

{284
if(System.trim(val) == '')return true;285
this.reg = /^[$¥]?(\d{1,3}(\,d{3})*|(\d+))(\.\d{2})?$/;286
this.msg="请输入金额,或以美元或人民币符合开头的数字,小数保留两位,如:¥1,000.00\r\n";287
return this.check(val);288
},289
isString:function(val)290

{291
if(System.trim(val) == '')return true;292
this.reg=/^\w+$/;293
this.msg="请输入规则字符串\r\n";294
return this.check(val);295
}, 296
isStringInteger:function(val)297

{298
if(System.trim(val) == '')return true;299
this.reg=/^[a-zA-Z][0-9]+$/;300
this.msg = "请输入首位是字母其他未数字的字符串\r\n";301
return this.check(val);302
},303
isStringOrInteger:function(val)304

{305
if(System.trim(val) == '')return true;306
this.reg=/^[a-zA-Z0-9]+$/;307
this.msg = "请输入字母或数字\r\n";308
return this.check(val);309
},310
isZip:function(val)311

{312
if(System.trim(val) == '')return true;313
this.reg=/^\d{6}$/;314
this.msg="请输入邮政编码,如:310000\r\n";315
return this.check(val);316
},317
isUnsignInteger:function(val)318

{319
if(System.trim(val) == '')return true;320
this.reg = /^\d*$/;321
this.msg = "请输入阿拉伯数字\r\n";322
return this.check(val);323
},324
isLetter:function(val)325

{326
if(System.trim(val) == '')return true;327
this.reg = /^[a-zA-Z]+$/;328
this.msg = "请输入英文字母\r\n";329
return this.check(val);330
},331
isChinese:function(val)332

{333
if(System.trim(val) == '')return true;334
this.reg=/^[\w\u00ff-\ufffd]+$/;335
this.msg = "请输入中文\r\n";336
return this.check(val);337
},338
maxLength:function(maxLen,val)339

{340
if(maxLen==0)return true;341
var len =System.trim(val).length;//this.strLength(val);342
if(len<=parseInt(maxLen))343
return true;344
this.msg = "输入的长度是实际"+len+",不能超过"+maxLen+"位\r\n";345
return false;346
},347
minLength:function(minLen,val)348

{349
if(minLen == 0)return true;350
var len = System.trim(val).length;351
if(len >= minLen)352
return true;353
this.msg = "输入的长度实际为"+len+",不能小于"+minLen+"位\r\n";354
return false;355
},356
///去字符长度,中文一个字占两个字符长度357
strLength:function(val)358

{359
var l = val.length;360
var n = l;361
for(var i = 0;i<l;i++)362

{363
if(val.charcodeat(i)<0 || val.charcodeat(i)>255)n++;364
}365
return n;366
},367
isDate:function(val)368

{369
if(val == "") return true;370
if(val.indexOf(':') < 0)371
val += ' 0:00:00';372

var r = val.match(/^(\d{1,4})(-|\/)(\d
{1,2})\2(\d
{1,2}) (\d
{1,2}):(\d
{1,2}):(\d
{1,2})$/);373
this.msg = "你输入的日期格式不正确\r\n";374
if(r == null) return false; 375
var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);376
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);377
} 378
});379

380

/**//*381
* 参数说明:382
* btnid:提交按钮 383
* focus是不是在用户离开控件就开始验证,true为是,false为在提交的时候才开始验证 384
* 页面设置说明:385
* regType:{386
* integer: 整型387
* float: 浮点型 388
* date: 日期格式389
* email: 电子游戏390
* letter: 26个英文字符 391
* chinese: 只允许中文392
* zip: 邮编393
* number:数字(0-9)394
* string: 常规字符395
* stringorinteger:数字与字符(a-Z,0-9)396
* stringInteger:首位字符,其余为数字397
* curreny: 货币398
* reg: 正则表达式,并且需提供 regex 属性399
* } 400
* maxLength:最大长度401
* minLength:最小长度402
* minValue:最小值403
* maxValue:最大值,minValue,maxValue只对regType值为integer与float有效404
* notnull:不能为空(如果可以为空,则不用设置405
* errorMsg:错误提示 406
* 页面应用举例:407
* <input regtype='integer' notnull maxLength="16" minLength="6" />408
* 409
*调用说明:410
* var formCheck = new System.FormCheck("btnid",{focus:true,formid:"form1" });411
* 412
*/413

/**//************************************414
* function System.FormCheck415
************************************/ 416
System.FormCheck = function(btnid,options)417


{418
///<summary>Provide support from form validate</summary>419
///<param name="btnid">The Button's identifier,the button which sumit the form to server </param>420
421
System.FormCheck.base.constructor.call(this);422
423
System.merge(this.options,424

{425
formid:'',426
focus:false427
});428
this.btnid = btnid;429
430
this.setOptions(options);431
this.addEventListener("onload",System.createDeletegate(this,this.onLoad));432
window.setTimeout(System.createDeletegate(this, this.checkLoadStatus),100);433
//this.init();434
}435
System.extend(System.Validate,System.FormCheck,436


{437
checkLoadStatus:function()438

{439
if(document.readyState && document.readyState !='loaded' && document.readyState != 'complete')return;441

461
window.setTimeout(System.createDeletegate(this, this.checkLoadStatus),100);462
return;463
}464
this.fireEvent("onload");465
},466
onLoad:function()467

{468
this.controls = [];469
var doc = null;470
if(typeof this.options.formid=='undefined' || this.options.formid=='')471

{472
doc = document.compatMode == "CSS1Compat" ? document.documentElement : document.body;473
}474
else475

{476
doc = document.getElementById(this.options.formid);477
}478
if(!doc)return;479
480
var inputs = doc.getElementsByTagName("INPUT");481
for(var i = 0;i<inputs.length;i++)482

{483
if(inputs[i].type.toLowerCase() =='text')484

{485
this.controls.push(inputs[i]);486
if(this.options.focus)487

{488
inputs[i].onblur = System.createDeletegate(this,this.Validate);489
}490
}491
}492
var textArea = doc.getElementsByTagName("TEXTAREA");493
for(var i = 0;i<textArea.length;i++)494

{495
this.controls.push(textArea[i]);496
if(this.options.focus)497

{498
textArea[i].onblur = this.Validate;499
}500
}501
this.register(this.btnid);502
},503
register:function(id)504

{ 505
var ctrl = document.getElementById(id);506
if(!ctrl)507
throw new Error("控件ID为"+id的对象不存在);508
var _oldClick = ctrl.onclick;509
if(_oldClick)510

{511
var obj = this;512
ctrl.onclick = function()513

{514
var flag = obj.Validate();515
if(flag) 516

{ 517
_oldClick(); 518
return true;519
}520
return false;521
}522
}523
else524

{525
ctrl.onclick =System.createDeletegate(this,this.Validate);526
}527
//ctrl.onclick = System.createDeletegate(this,this.Validate);528
//ctrl.onclick = this.Validate; 529
//this.addEventListener("onclick",System.createDeletegate(ctrl,this.Validate));530
},531
//判断控件是否可见,style.display,visibility 532
isHidden:function(ctrl)533

{534
if(ctrl.display == 'none' && ctrl.style.visibility=='hidden')535

{536
return true;537
}538
ctrl = ctrl.parentNode;539
while(ctrl.tagName != 'BODY')540

{541
if(ctrl.style.display == 'none' || ctrl.style.visibility=='hidden')542

{543
return true;544
}545
ctrl = ctrl.parentNode;546
}547
return false;548
}, 549
Validate:function()550

{ 551
var sign = true;552
var msg = "";553
var firstNode = null;554
for(var i =0;i<this.controls.length;i++)555

{556
if(this.isHidden(this.controls[i]))continue;557
var type = this.controls[i].getAttribute("regType")||"";558
var value = this.controls[i].value||"";559
value = System.trim(value);560
var falg;561
switch(type.toLowerCase())562

{563
case "integer": 564
flag = this.isInteger(value);565
if(flag && value != "")566

{567
var minValue = this.controls[i].getAttribute("minValue")||"";;568
var maxValue = this.controls[i].getAttribute("maxValue")||"";569
if(minValue!="")570

{571
if(parseInt(minValue) >parseInt(value))572

{573
this.msg = "值不能小于"+minValue+'\r\n';574
flag = false;575
}576
}577
if(flag && maxValue!="")578

{579
if(parseInt(maxValue)<parseInt(value))580

{ 581
this.msg ="值不能大于"+maxValue+'\r\n';582
flag = false;583
} 584
}585
}586
break;587
case "float":588
flag = this.isDouble(value);589
if(flag && value != "")590

{591
var minValue = this.controls[i].getAttribute("minValue")||"";;592
var maxValue = this.controls[i].getAttribute("maxValue")||"";593
if(minValue!="")594

{595
if(parseFloat(minValue) >parseFloat(value))596

{597
this.msg = "值不能小于"+minValue;598
flag = false;599
}600
}601
if(flag && maxValue!="")602

{603
if(parseFloat(maxValue)<parseFloat(value))604

{605
this.msg ="值不能大于"+maxValue;606
flag = false;607
} 608
}609
}610
break;611
case "date":612
flag = this.isDate(value);613
break;614
case "string":615
flag = this.isString(value);616
break;617
case "stringorinteger":618
flag = this.isStringOrInteger(value);619
break;620
case "stringinteger":621
flag = this.isStringInteger(value);622
break;623
case "letter":624
flag = this.isLetter(value);625
break;626
case "zip":627
flag = this.isZip(value);628
break;629
case "email":630
flag = this.isEmail(value);631
break;632
case "chinese":633
flag = this.isChinese(value);634
break;635
case "number":636
flag = this.isUnsignInteger(value);637
break;638
case "curreny":639
flag = this.isCurreny(value);640
break;641
case "reg":642
var reg = this.controls[i].getAttribute("regex");643
if(reg)644
flag = this.regex(value,reg);645
flag = true;646
break;647
} 648
if(sign)sign = flag; 649
if(sign == false)650

{651
if(firstNode == null)652

{653
firstNode = this.controls[i];654
}655
if(this.controls[i].getAttribute("errorMsg"))656
msg +=this.controls[i].getAttribute("errMsg")+"\r\n";657
else if(this.msg != '')658

{659
msg +=this.msg; 660
}661
this.msg = ""; 662
if(this.options.focus)663

{664
break;665
} 666
}667
else 668

{669
var maxLength = this.controls[i].getAttribute("maxLength");670
if(maxLength)671

{672
flag = this.maxLength(maxLength,value);673
}674
sign = flag; 675
var minLen = this.controls[i].getAttribute("minLength");676
if(minLen)677

{678
flag = this.minLength(minLen,value);679
msg +=this.msg+"\r\n";680
}681
if(sign)sign = flag;682
if(this.controls[i].getAttribute("notnull") !=null)683

{684
if(System.trim(value) == "")685

{686
if(firstNode == null)687

{688
firstNode = this.controls[i];689
}690
flag =false;691
msg = "内容不能为空";692
}693
}694
if(sign)sign = flag;695
if(this.options.focus && sign==false)696

{697
break;698
}699
}700
}701
if(sign == false)702

{703
alert(msg);704
firstNode.select();705
firstNode.focus(); 706
}707
delete msg;708
event.returnValue=sign;709
return sign;710
this.firEvent('validateComplete');711
}712
});由于没有太多的时间,并且代码中已经有比较详细的说明,所以就不在过多解释了,由于脚本刚完成不久,所以可能还存在问题。
以后有时间的话,会解释脚本中类的继承的实现。
脚本下载

浙公网安备 33010602011771号