validate.js页面验证js使用方法

validate.js包含三个主要的构造: FormValidatorInputValidatorBaseValidator构造会new一个对象,对有限属性进行覆盖:

  FormValidator是表单的验证构造,需要两个参数,第一个为表单元素,第二个为构造的参数列表(是一个JSON对象会覆盖掉该对象中的同名属性)。

  InputValidator 是表单元素的验证构造,有三个参数,第一个参数为该对象的宿主对象(元素所在的form对象,如果传入Null则会自动查找所在form),第二个参数为表单元素,第三个参数为构造属性(是一个JSON对象会覆盖掉该对象中的同名属性)。

  BaseValidator为所有验证规则的基础构造,构造包含两个参数第一个参数为验证规则的宿主对象(一般为InputValidator),第二个参数是验证规则的参数列表对象(是一个JSON对象会覆盖掉该对象中的同名属性)。

  在使用时不需要手动调用构造参数,框架已将构造过程嵌入到了JQuery对象中,只需要用JQuery查找到对象,然后调用elementValidator方法(或同名方法initValidator)就会根据元素类型(tagName是否form)获得相应的对象(FormValidatorInputValidator),方法需要一个参数用来覆盖掉对象中的默认成员。

  需要使用InputValidator对象的addValidator方法构造BaseValidator对象,addValidator包含两个参数第一个参数为验证规则名称(必须是已注册的验证规则),第二个参数是用来覆盖掉验证规则对象默认成员的JSON对象,关于注册规则将在最后说明。

 

2. 使用方法

 

2.1 初始化验证的表单

  在页面的load事件中调用$("#表单ID").elementValidator(或同名方法initValidator),该方法参数为JSON Object

  $("#sForm").elementValidator({

  autoSubmit : true,//验证通过后是否自动提交表单(默认为true,自动提交)

  failStop:false,//验证表单项时 某一元素验证失败是否终止验证程序(默认为false,每次表单验证都会验证全部元素)

  exceptionFail:true,//验证过程中出现异常是否标记为验证失败(默认为true)

  beforeValidate:false,//在验证之前执行的方法,如果该方法返回false则不再进行验证,并返回false

  onFail:function(callback){},//验证失败会调用的方法,默认是一个空方法

  onVali:function(callback){}//验证通过会调用的方法,默认是一个空方法

  });

  //****参数不填均为默认值

 

2.2 初始化需要验证的表单项

  在页面的load事件中调用$("#元素ID").elementValidator(或同名方法initValidator) ,该方法参数为JSON Object,调用该方法会返回一个InputValidator对象,然后通过该对象的addValidator(RuleName,{/*RuleOption*/})方法添加验证规则

  (不需要的参数不要填写填写之后便会覆盖掉默认的值,以下均为默认值)

  $('#Email').initValidator({

  autoBind :true,//是否自动绑定验证到元素的事件(会绑定change,focus,blur,changeblur时会进行验证)

  msgTarget : 元素ID + "_tip",//验证反馈元素的ID,用来显示验证结果,默认为元素ID + "_tip"

  readyMsg  "",//初始状态消息

  focusMsg: "",//获取焦点后的消息

  validMsg  "",//验证通过后的消息

  waitMsg  "",//等待状态的消息

  errorMsg  "",//验证错误的消息

  againMsg  "",//重试的消息

  readyClass: 'validation-ready',//初始状态的CSS样式

  errorClass  'validation-error',//错误状态的CSS样式

  focusClass:'validation-focus',//获取焦点的CSS样式

  validClass:'validation-valid',//验证通过的CSS样式

  waitClass  'validation-wait',//等待状态的CSS样式

  againClass  'validation-error',//需要重试的CSS样式

  allowEmpty  false//是否允许为空当设置为true如果元素的值未填则不会进行验证,并设置该元素的验证状态为通过

  affected null,//affected元素的change事件会影响到该元素的状态状态取决于affectState的值

  affectState:"ready",//默认为ready状态

  showMsg : function(state, message{//显示该元素验证消息的方法,会覆盖掉默认显示消息方法,如果使用默认的显示消息方法,请确保不要包含该条属性

  message message || this[state "Msg"];

  var msgTarget $("#" this.msgTarget);

  msgTarget.removeClass().addClass(this[state "Class"]).html(message);

  },

  }).addValidator('NotNull', {//添加非空验证

  errorMsg : '请输入邮箱地址'

  }).addValidator('Email', {//添加邮箱格式验证

  errorMsg : '邮箱格式错误,请重新输入'

  }).addValidator('URLValue', {//添加URL资源文本验证

  url : 'validate',

  sendData : {

  'type' : 'email'

  },

  sendKey : 'Email',

  eqValue : 'false',

  errorMsg : '该邮箱已被注册,请重新输入'

  });

 

2.3 默认已实现的验证规则

  (1)NotNull (非空验证)

  参数:

  autoTrim 是否在验证前执行Trim操作(去除文本两端半角空格默认为false

 

  (2)RegExp 正则表达式验证

  参数

  autoTrim 是否在验证前执行Trim操作(去除文本两端半角空格默认为false

  regex  正则表达式(字符串)

  attr  可选的字符串,包含属性 "g""i" 和 "m",分别用于指定全局匹配、区分大小写的匹配和多行匹配

 

  (3)Email 邮箱格式验证

  参数:

  autoTrim 是否在验证前执行Trim操作(去除文本两端半角空格默认为false

  errorMsg 默认:"电子邮箱格式错误"

  Regex 默认: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)+$"

 

  (4)Length 长度校验

  参数

  min最小长度(-1为不限)

  max最大长度(-1为不限)

  lable提示时的标识名称(比如该值如果是用户名,当元素值不满足条件会提示:用户名长度应大于或小于xx个字符)

 

  (5)Equals 对比校验

  参数:

  eqElement: '', //比较的元素(优先级大于eqValue)

  eqValue: '', //比较的值(eqElement不为空时不会比较该值)

 

  (6)URLValue URL资源对比(该校验可以做页面 验证码,用户名是否存在等ajax校验)

  参数:

  isSync: false, //是否同步模式

  url: "", //URL

  method: "post", //提交方式

  sendData: {}, //提交的值

  sendKey: "", //提交URL请求时,使用的数据name

  eqValue: "", //对比值-将请求URL得到的文本与该值对比

 

  (7)Attr 属性校验(校验元素的属性值)

  参数:

  attr: "value", //属性名称

  eqValue: null, //属性对比值

  val: function(input){//默认的获取属性值的方法

  return $(input).attr(this.attr);

  }

 

  (8)Number 数值验证(数值大小不能超出JS的数值范围-1.7976931348623157e+308 ~ 1.7976931348623157e+308)

  参数:

  onlyInt: false, //是否验证为整数

  min: null, //最小值(默认null为不限制)

  max: null, //最大值(默认null为不限制)

 

  (9)Int 整数验证(继承至Number 验证)

  属性:

  onlyInt: true

 

  (10)Function Function验证

  参数:

  func: "",字符串或function对象,该方法需要返回Booleantruefalse

  root: window,function属性为字符串的时候将会在该对象下根据func的值查找function,如果查找不到则提示:验证方法(" + func + ")未找到

 

2.4 注册验证规则

  使用$.validation.regRules方法注册验证规则,该方法有三个参数:

  参数1:验证规则名称,比如:Email,NumberNotNull;

  参数2:验证规则属性,需要包含 doValidate: function(input, waitToDo){}的函数实现,该方法返回true,false,或'wait','again'表示验证成功,验证失败,等待,重试,该方法包含两个参数,参数input表示验证的页面元素,waitToDo是在异步验证回调时使用;

  参数3(可选):该验证规则继承来源,表示该验证规则继承至另一个验证规则,可以使用this.superDoValidate得到父验证规则的验证方法,并可以使用父验证规则的属性。

  举例:URLValue验证,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$.validation.regRules('URLValue', {//URL资源,值验证
  isSync: false, //非同步
  url: "", //URL
  method: "post", //提交方式
  sendData: {}, //提交的值
  sendKey: "", //表单元素名
  eqValue: "", //对比值
  doValidate: function(input, waitToDo){
      this.sendData[this.sendKey || $(input).attr('name') || $(input).attr('id')] = this.val(input);
      var ajaxSend = function(v, waitToDo){//ajax请求数据
          $.ajax({
              url: v.url,
              type: v.method,
              cache: false,
              data: v.sendData,
              success: function(data){
                  var result = false;
                  if (data === v.eqValue) {
                      result = true;
                  }
                  else {
                      result = false;
                  }
                  waitToDo(result);//获取数据后执行waitToDo
              },
              error: function(xhr, text){//ajaxError处理
                  var errorMessage = "与服务器通信失败,请稍候再试";
                  waitToDo("again", errorMessage);
              }
          });
      }(this, waitToDo);
      return "wait";//返回等待状态
  }

 

2.5 页面使用示例

  ZAS注册页面

<z:config type="zas" name="注册模板"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>用户注册</title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/validate.js"></script>
<script>
$(function() {
var enableUserNameCN = $("#EnableUserNameCN").val();
var regex = '^[a-zA-Z0-9_]*$';
var errorMsg = '只能使用英文、数字、下划线';
var focusMsg = '4~24位字符,可使用英文、数字、下划线';
if(enableUserNameCN=='Y'){
regex = '^[a-zA-Z0-9_\u4e00-\u9fa5]*$';
errorMsg = '只能使用英文、数字、中文、下划线';
focusMsg = '4~24位字符,可使用英文、数字、下划线、中文';
}
$('#registerForm').initValidator({
autoSubmit:true,
});
$('#UserName').initValidator({
readyMsg : '必填',
focusMsg : focusMsg,
msgTarget : 'tipname'
}).addValidator('NotNull', {
errorMsg : '请输入用户名'
}).addValidator('Length', {
min : 4,
max : 24,
errorMsg : '至少使用4位字符'
}).addValidator('RegExp', {
regex : '^(?!_)(?!.*?_$)',
errorMsg : '不能以下划线开头或结尾'
}).addValidator('RegExp', {
regex : regex,
errorMsg : errorMsg
// regex : '^[a-zA-Z0-9_]*$',
// errorMsg : '只能使用英文、数字、下划线'
}).addValidator('URLValue', {
url : 'validate',
eqValue : 'false',
sendData : {
'type' : 'username'
},
sendKey : 'UserName',
errorMsg : '该用户名已被使用,请重新输入。如果您拥有该用户名,请立即<a href="${contextPath}${sso_login}" style="color:red;">登录</a>'
});
 
$('#Password').initValidator({
readyMsg : '必填',
focusMsg : '6-16位字符,区分大小写',
msgTarget : 'tippassword'
}).addValidator('NotNull', {
errorMsg : '请输入密码'
}).addValidator('Length', {
min : 6,
max : 16,
errorMsg : '密码应为6-16位字符,区分大小写'
});
 
$('#pwdok').initValidator({
readyMsg : '必填',
focusMsg : '请再次输入密码',
msgTarget : 'tippwdok',
affected : '#Password',
affectState : 'focus'
}).addValidator('NotNull', {
errorMsg : '请输入确认密码'
}).addValidator('Equals', {
eqElement : '#Password',
errorMsg : '两次输入的密码不一致,请重新输入'
});
 
$('#Email').initValidator({
readyMsg : '必填',
focusMsg : '请输入您的常用邮箱,以便密码丢失时找回密码',
msgTarget : 'tipemail'
}).addValidator('NotNull', {
errorMsg : '请输入邮箱地址'
}).addValidator('Email', {
errorMsg : '邮箱格式错误,请重新输入'
}).addValidator('URLValue', {
url : 'validate',
sendData : {
'type' : 'email'
},
sendKey : 'Email',
eqValue : 'false',
errorMsg : '该邮箱已被注册,请重新输入'
});
 
$('#AuthCode').initValidator({
readyMsg : '必填',
focusMsg : '请输入验证码',
msgTarget : 'tipauthcode'
}).addValidator('NotNull', {
errorMsg : '请输入验证码'
}).addValidator('URLValue', {
url : 'validate',
sendData : {
'type' : 'authcode'
},
sendKey : 'AuthCode',
eqValue : 'true',
errorMsg : '验证码错误,请重新输入'
});
 
$("#Checkbox").initValidator({
readyClass:'',
focusClass:'',
validClass:'',
msgTarget : 'tipcheckbox'
}).addValidator("Attr",{
errorMsg : '请先阅读并接受《用户注册协议》',
attr:'checked'
});
});
 
function initAuthCode() {
$('#AuthCode').attr('value', '');
}
 
</script>
</head>
<body>
 
<z:include file="${template}header.zhtml"/>
<div class="main pageWidth">
<input type="hidden" name="EnableUserNameCN" id="EnableUserNameCN" value="${EnableUserNameCN}" />
<form id="registerForm" name="registerForm" method="post">
<input type="hidden" name="Referer" id="Referer" value="${Referer}" />
<input type="hidden" name="Type" id="Type" value="register" />
<div class="mod_com">
<div class="mod_comtitle"><h2>用户注册</h2></div>
<div class="mod_mainbox">
<table width="740" border="0" cellspacing="0" cellpadding="0" class="registerWrap_mainboxtable">
<tbody>
<z:if condition="${EnableUserNameCN=='Y'}">
<tr>
<td width="96" align="right">用户名:</td>
<td colspan="2" align="left"><input type="text" id=UserName name="UserName" class="logintext1" maxlength="24"></td>
<td width="500" align="left"><span id="tipname" class="validation-ready"></span></td>
</tr>
</z:if>
<z:else>
<tr>
<td width="96" align="right">用户名:</td>
<td colspan="2" align="left"><input type="text" id=UserName name="UserName" class="logintext1" maxlength="24"></td>
<td width="420" align="left"><span id="tipname" class="validation-ready"></span></td>
</tr>
</z:else>
<tr>
<td align="right">密 码:</td>
<td colspan="2" align="left"><input type="password" id="Password" name="Password" class="logintext1" maxlength="16"/></td>
<td align="left"><span id="tippassword" class="validation-ready"></span></td>
</tr>
<tr>
<td align="right">确认密码:</td>
<td colspan="2" align="left"><input type="password" id="pwdok" name="pwdok" class="logintext1" maxlength="16"/></td>
<td align="left"><span id="tippwdok" class="validation-ready"></span></td>
</tr>
<tr>
<td align="right">邮 箱:</td>
<td colspan="2" align="left"><input type="text" id="Email" name="Email" class="logintext1" maxlength="80"/></td>
<td align="left"><span id="tipemail" class="validation-ready"></span></td>
</tr>
<tr>
<td width="200" align="right">工作(扩展):</td>
<td colspan="2" align="left"><input type="text" id=job name="MetaValue_job" class="logintext1" maxlength="24"></td>
<td width="420" align="left"><span id="tipname" class="validation-ready"></span></td>-->
</tr>
<tr>
<td align="right">验证码:</td>
<td width="157" align="left"><input type="text" id="AuthCode" name="AuthCode" class="logintext2" maxlength="10"/></td>
<td width="89" align="left"><img id="authcode" src="${contextPath}authCode.zhtml" οnclick="$('#authcode').attr('src','authCode.zhtml?'+new Date().getTime());initAuthCode();return false;" style="vertical-align:middle; margin-left:4px;"/></td>
<td align="left"><label for="authcode">看不清?换一张</label>&nbsp;&nbsp;&nbsp;<span id="tipauthcode" class="validation-ready"></span></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td colspan="2" align="left" valign="bottom"><input type="checkbox" id="Checkbox" name="Checkbox">我已经阅读并接受《<span><a href="${contextPath}protocal" class="blue" target="_blank">用户注册协议</a></span>》</td>
<td align="left"><span id="tipcheckbox"></span></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td colspan="3" align="left" style="padding-top:20px;"><input type="submit" class="linkbtn" value="立即注册"/></td>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</div>
 
<z:include file="${template}footer.zhtml"/>
</body>
</html>
 
附(validate.js源码):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//创建命名空间
$ = $ || {};
$.validation = {
    Version: "20130830_Beta",
    Company: "www.zving.com",
    Author: "[email protected]",
    UseFrame: "JQuery(使用了JQuery的查找器及属性/样式/事件绑定方法)",
    OpenTags: ["from", "input", "select", "textarea", "button"]
};
/**
 * 复制对象属性至指定对象,若未指定复制到的对象则返回一个新对象,包含原对象所有属性
 * @param {Object} copyFrom 从该对象复制
 * @param {Object} copyTo 复制到的对象  若为Null或不传该参则返回copyFrom的拷贝
 */
$.validation.copy = function(copyFrom, copyTo){
    if (copyTo) {
        for (var i in copyFrom) {
            copyTo[i] = copyFrom[i];
        }
    }
    else {
        var p = function(){
        };
        p.prototype = copyFrom;
        return new p();
    }
};
/***
 * 判断值是否存在数组或对象中
 * @param {Object} value 判断的值
 * @param {Object} array 判断所在数组或对象
 * @return {Boolean}
 */
$.validation.inArray = function(value, array){
    for (var i in array) {
        if (value === array[i]) {
            return true;
        }
    }
    return false;
};
/**
 * 注册规则
 * @param {String} rule 规则名称
 * @param {Object} options 选项
 * @param {String} extendRule 继承至哪个规则
 */
$.validation.regRules = function(rule, options, extendRule){
    $.validation.ruleOptions = $.validation.ruleOptions || {};
    if (typeof(extendRule) === "string") {
        $.validation.ruleOptions[rule] = {};
        $.validation.ruleOptions[rule].superRule = $.validation.copy($.validation.ruleOptions[extendRule]);
        $.validation.copy($.validation.ruleOptions[rule].superRule, $.validation.ruleOptions[rule]);
        $.validation.copy(options, $.validation.ruleOptions[rule]);
    }
    else {
        $.validation.ruleOptions[rule] = $.validation.copy(options);
    }
    return this;
};
 
/**
 *验证构造
 * @param paras {Object} 寄宿对象(一般为InputValidator对象)
 * @param options {Object}参数  :
 * {
 *  isSync {Boolean} //是否为同步验证(默认为true)
 *  errorMsg {String} //错误提示消息(默认为"")
 *  doValidate(input, waitToDo) {Function} //验证方法,如果要验证生效必须重写(返回true,false,或'wait','again')
 *                              异步验证需在异步回调中调用waitToDo(result, message),result为验证状态,message为返回的消息
 *  val(input) {Function} //获取元素值的方法,可重写,默认采用jquery的val()方法,可重写获取其他要验证的值
 * }
 */
$.validation.BaseValidator = function(paras, options){
    this.isSync = true;
    //是否同步验证
    this.ruleName = '';
    //规则名称
    this.errorMsg = '';
    //验证错误时返回的消息
    this.cache = true;
    //是否缓存验证结果(当表单元素值未改变时会使用缓存验证值)
     
    /**
     *
     */
    this.doValidate = function(input, waitToDo){
        return true || false || "wait";
    };
    this.val = function(input){
        return $(input).val();
    };
    $.validation.copy(options, this);
    //支持覆盖的自定义属性 --结束
     
    this.lastResult = null;
    this.nextor = null;
    //验证通过后要进行的下一个验证
     
    //重置验证状态
    this.resetValiState = function(){
        this.lastResult = null;
        this.lastValue = null;
        if (this.nextor) {
            return this.nextor.resetValiState();
        }
    };
    /**
     *执行继承源的 doValidate
     */
    this.superDoValidate = function(input, waitToDo){
        if (this.superRule && typeof(this.superRule.doValidate === 'function')) {
            return this.superRule.doValidate.apply(this, arguments);
        }
    };
     
    this.validate = function(input, CallBack, eventFrom){
        var result = false;
        if (this.cache && this.val(input) === this.lastValue) {
            if (this.lastResult) {
                if (this.lastResult.state === "again") {
                    var returnValue = this.lastResult;
                    this.lastResult = null;
                    return returnValue;
                }
                if (this.nextor && this.lastResult.state === "valid") {
                    return this.nextor.validate(input, CallBack, eventFrom);
                }
                else {
                    return this.lastResult;
                }
            }
        }
        var waitToDo = this.isSync ||
        function(validator, input, CallBack, eventFrom){
            return function(result, message){
                validator.lastResult = validator.buildResult(result, message);
                validator.lastValue = validator.val(validator.paras.input);
                if (result === true && eventFrom && eventFrom === "form") {
                    validator.paras.paras.validator.validate(CallBack);
                }
                else {
                    validator.paras.validate(input, CallBack);
                }
                return validator;
            };
        }(this, input, CallBack, eventFrom);
        result = this.doValidate(input, waitToDo);
        this.lastResult = this.buildResult(result);
        this.lastValue = this.val(input);
        if (result === true) {
            if (this.nextor) {
                return this.nextor.validate(input, CallBack, eventFrom);
            }
        }
        return this.lastResult;
    };
     
    this.buildResult = function(result, message){
        var vResult = {
            rule: this.ruleName
        };
        if (result === true) {
            vResult.state = "valid";
        }
        else
            if (result === false) {
                vResult.message = message || this.errorMessage || this.errorMsg;
                this.errorMessage = null;
                vResult.state = "error";
            }
            else
                if (typeof(result) === "string") {
                    vResult.state = result;
                    vResult.message = message || this[result + "Message"] || this[result + "Msg"];
                    if (this[result + "Message"]) {
                        this[result + "Message"] = null;
                    }
                }
                else {
                    vResult.state = "ready";
                    vResult.message = message || this["readyMessage"] || this["readyMsg"];
                    if (this["readyMessage"]) {
                        this["readyMessage"] = null;
                    }
                }
        return vResult;
    };
     
    this.paras = paras;
};
/***
 *
 * @param options {Object}参数  :
 * {
 *  msgTarget {Boolean} //是否为同步验证(默认为true)
 *  readyMsg {String} //错误提示消息(默认为"")
 *  focusMsg {String} //错误提示消息(默认为"")
 *  validMsg {String} //错误提示消息(默认为"")
 *  waitMsg {String} //错误提示消息(默认为"")
 *  readyClass {String} //错误提示消息(默认为"")
 *  errorClass {String} //错误提示消息(默认为"")
 *  focusClass {String} //错误提示消息(默认为"")
 *  validClass {String} //错误提示消息(默认为"")
 *  focusMsg {Function} //验证方法(返回true,false,或'wait')
 * }
 */
$.validation.InputValidator = function(paras, input, options){
    //支持覆盖的自定义属性 --开始
    this.autoBind = true;
    this.msgTarget = input.id + "_tip";
    this.readyMsg = "";
    this.focusMsg = "";
    this.validMsg = "";
    this.waitMsg = "";
    this.errorMsg = "";
    this.againMsg = "";
    this.readyClass = 'validation-ready';
    this.errorClass = 'validation-error';
    this.focusClass = 'validation-focus';
    this.validClass = 'validation-valid';
    this.waitClass = 'validation-wait';
    this.againClass = 'validation-error';
    this.allowEmpty = false;
    this.affected = null;
    this.affectState = "ready";
    this.queueElement = null;
    this.showMsg = function(state, message){
        message = message || this[state + "Msg"];
        var msgTarget = $("#" + this.msgTarget);
        msgTarget.removeClass().addClass(this[state + "Class"]).html(message);
    };
     
    //支持覆盖的自定义属性 --结束
    $.validation.copy(options, this);
    this.input = input;
    this.firstValidator = null;
    this.lastValidator = null;
    this.validate = function(callBack, eventFrom){
        if (this.queueElement != null) {
            var qElement = $(this.queueElement)[0];
            if (qElement && qElement.validator && qElement.validator.validate().state !== "valid") {
                this.showMsg("ready");
                return {
                    state: "ready"
                };
            }
        }
        if (this.allowEmpty === true && $(this.input).val() === '') {
            this.showMsg("ready");
            return {
                state: "valid"
            };
        }
        if (this.firstValidator) {
            var result = this.firstValidator.validate(this.getElement(), callBack, eventFrom);
            this.showMsg(result.state, result.message);
            return result;
        }
    };
     
    this.resetValiState = function(state){
        this.firstValidator.resetValiState();
        this.showMsg(state);
    };
     
    this.addValidator = function(rule, options){
        var ruleOptions = $.validation.copy($.validation.ruleOptions[rule]);
        $.validation.copy(options, ruleOptions);
        if (this.affected) {
            ruleOptions.cache = false;
        }
        var newValidator = new $.validation.BaseValidator(this, ruleOptions);
        newValidator.ruleName = rule;
        if (this.firstValidator == null) {
            this.firstValidator = newValidator;
        }
        else {
            this.lastValidator.nextor = newValidator;
        }
        this.lastValidator = newValidator;
    };
    if (this.autoBind) {
        $(input).bind("change", function(v){
            return function(){
                v.validate();
            };
        }(this)).bind("focus", function(v){
            return function(){
                v.showMsg("focus");
            };
        }(this)).bind("blur", function(v){
            return function(){
                v.validate();
            };
        }(this));
    }
    if (this.affected) {
        $(this.affected).bind("change", function(v, state){
            return function(){
                v.resetValiState(state);
                if ($(v.input).val() !== "") {
                    $(v.input).focus();
                }
            };
        }(this, this.affectState));
    }
    this.getElement = function(){
        return $(this.input)[0];
    };
    $(input)[0].validator = this;
    this.showMsg("ready");
    this.paras = paras;
    if (!this.paras) {
        this.paras = this.getElement().form;
    }
};
$.validation.FormValidator = function(form, options){
    this.autoSubmit = true;
    this.failStop = false;
    this.exceptionFail = true;
    this.onFail = function(callBack){
        return false;
    };
    this.onVali = function(callBack){
        return true;
    };
    this.beforeValidate = null;
    $.validation.copy(options, this);
    this.form = form;
    //支持覆盖的自定义属性 --结束
     
    this.validate = function(callback){
        if (this.beforeValidate && typeof(this.beforeValidate) === 'function') {
            if (!this.beforeValidate()) {
                return false;
            }
        }
        var elements = this.form.elements;
        var valid = true;
        try {
            for (var i = 0; i < elements.length; i++) {
                var element = elements[i];
                if (element.validator && typeof(element.validator.validate) === 'function') {
                    var result = element.validator.validate(callback, "form");
                    if (result.state !== 'valid') {
                        valid = false;
                        if (this.failStop) {
                            onFail(callback);
                            return valid;
                        }
                    }
                }
            };
                    }
        catch (e) {
            valid = (!exceptionFail) && valid;
        }
        if (valid) {
            this.onVali(callback);
        }
        else {
            this.onFail(callback);
        }
        if (this.autoSubmit === true) {
            return this.submit(valid);
        }
        return valid;
    };
    this.submit = function(valid){
        if (valid === true) {
            $(this.form)[0].submit();
        }
        return false;
    };
     
    $(this.form).bind("submit", function(validator){
        return function(){
            var valid = validator.validate(validator.callBack);
            return valid;
        };
    }(this));
    $(this.form)[0].validator = this;
};
 
$.fn.elementValidator = function(options){
    var element = this[0];
    if (!element) {
        return {
            addValidator: function(){
                return this;
            }
        };
    }
    if (element.validator) {
        $.validation.copy(options, element.validator);
    }
    else {
        var tagName = (element.tagName || element.nodeType).toLowerCase();
        if (tagName === 'form') {
            element.validator = new $.validation.FormValidator(element, options);
        }
        else {
            element.validator = new $.validation.InputValidator(null, element, options);
            return this;
        }
    }
};
$.fn.initValidator = $.fn.elementValidator;
$.fn.addValidator = function(rule, options){
    //alert(rule);
    var element = this[0];
    if (element.validator && typeof(element.validator.addValidator) === 'function') {
        element.validator.addValidator(rule, options);
        return this;
    }
};
 
$.validation.regRules("Base", {
    autoTrim: false, //是否自动去掉字符串两端的空格
    trim: function(input){
        var value = $(input).val();
        if (typeof(value) === 'string') {
            value = value.replace(/(^\s*)|(\s*$)/g, "");
        }
        else {
            value = '';
        }
        $(input).val(value);
        return value;
    }
}).regRules("NotNull", {//非空验证
    doValidate: function(input, waitToDo){
        var value = this.autoTrim ? this.trim(input) : $(input).val();
        if (value.length > 0) {
            return true;
        }
        return false;
    }
}, "Base").regRules("RegExp", {//正则验证
    regex: "",
    attr: "",
    doValidate: function(input, waitToDo){
        var reg = this.regex;
        if (typeof(reg) === "string") {
            reg = new RegExp(reg, this.attr);
        }
        else
            if (!typeof(reg.test) === 'function') {
                return false;
            }
        return reg.test(this.val(input));
    }
}).regRules("Email", {//Email格式验证
    errorMsg: "电子邮箱格式错误",
    regex: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)+$"
}, "RegExp").regRules("Length", {//字符串长度验证
    min: -1, //最短长度(-1为不限)
    max: -1, //最大长度(-1为不限)
    lable: "", //提示时的标识名称
    doValidate: function(input, waitToDo){
        var value = this.autoTrim ? this.trim(input) : $(input).val();
        var result = true;
        var valStrLen = value.length;
        if (this.min !== -1) {
            if (valStrLen < this.min) {
                result = false;
            }
        }
        if (this.max > -1) {
            if (valStrLen > this.max) {
                result = false;
            }
        }
        if (result == false && this.errorMsg == "") {
            this.setMessage();
        }
        return result;
    },
    setMessage: function(){
        this.errorMsg = this.lable + "长度应";
        if (this.max === -1) {
            this.errorMsg += "大于" + this.min + "个字符";
        }
        else
            if (this.min === -1) {
                this.errorMsg += "小于" + this.max + "个字符";
            }
            else {
                this.errorMsg += "在" + this.min + "与" + this.max + "个字符之间";
            }
    }
}, "Base").regRules("Async", {//异步
    isSync: false
}).regRules("Equals", {//比较
    eqElement: '', //比较的元素(优先级大于eqValue)
    eqValue: '', //比较的值(当eqElement不为空时不会比较该值)
    doValidate: function(input, waitToDo){
        if (this.eqElement) {
            return this.val(this.eqElement) === this.val(input);
        }
        else {
            return this.val(input) === this.eqValue;
        }
    }
}).regRules('URLValue', {//URL资源,值验证
    isSync: false, //非同步
    url: "", //URL
    method: "post", //提交方式
    sendData: {}, //提交的值
    sendKey: "", //表单元素名
    eqValue: "", //对比值
    doValidate: function(input, waitToDo){
        this.sendData[this.sendKey || $(input).attr('name') || $(input).attr('id')] = this.val(input);
        var ajaxSend = function(v, waitToDo){
            $.ajax({
                url: v.url,
                type: v.method,
                cache: false,
                data: v.sendData,
                success: function(data){
                    var result = false;
                    if (data === v.eqValue) {
                        result = true;
                    }
                    else {
                        result = false;
                    }
                    waitToDo(result);
                },
                error: function(xhr, text){
                    var errorMessage = "与服务器通信失败,请稍候再试";
                    waitToDo("again", errorMessage);
                }
            });
        }(this, waitToDo);
        return "wait";
    }
}).regRules("Attr", {//属性验证
    attr: "value", //属性名称
    eqValue: null, //属性对比值
    val: function(input){
        return $(input).attr(this.attr);
    },
    doValidate: function(input, waitToDo){
        if (this.eqValue) {
            return this.val(input) === this.eqValue;
        }
        else {
            return this.val(input) ? true : false;
        }
    }
}).regRules("Number", {//数值验证(数值大小不能超出JS的数值范围-1.7976931348623157e+308 ~ 1.7976931348623157e+308)
    onlyInt: false, //是否验证为整数
    min: null, //最小值(默认null为不限制)
    max: null, //最大值(默认null为不限制)
    doValidate: function(input, waitToDo){
        var numberValue = null;
        if (onlyInt) {
            numberValue = parseInt(this.val(input));
            var notInt = (numberValue.toString() !== this.val(input));
            if (notInt) {
                return false;
            }
        }
        else {
            numberValue = parseFloat(this.val(input));
            if (v !== v) {
                return false;
            }
            else
                if (v === Infinity) {
                    this.errorMessage = "超出数值范围最大值";
                    return false;
                }
                else
                    if (v === -Infinity) {
                        this.errorMessage = "超出数值范围最小值";
                        return false;
                    }
        }
        if (min !== null) {
            if (numberValue < min) {
                return false;
            }
        }
        if (max !== null) {
            if (numberValue > max) {
                return false;
            }
        }
        return true;
    }
}).regRules("Int", {//整数验证(继承至数值验证)
    onlyInt: true
}, "Number").regRules("Function", {
    func: "",
    root: window,
    doValidate: function(input, value){
        var func = this.func;
        var doFunction = null;
        if (func) {
            var tpFunc = typeof(func);
            if (tpFunc === "string") {
                var fname = this.func;
                var cmIndex = -1;
                var funObj = this.root;
                do {
                    cmIndex = fname.indexOf('.');
                    if (cmIndex === -1) {
                        if (funObj && funObj[fname]) {
                            doFunction = funObj[fname];
                            break;
                        }
                        else {
                            this.errorMessage = "验证方法(" + this.func + ")未找到";
                            return false;
                        }
                    }
                    else {
                        var subName = fname.substring(0, cmIndex);
                        if (funObj && funObj[subName]) {
                            funObj = funObj[subName];
                            fname = fname.substring(cmIndex + 1);
                        }
                        else {
                            this.errorMessage = "验证方法(" + this.func + ")未找到";
                            return false;
                        }
                    }
                }
                while (true);
            }
            else {
                doFunction = tpFunc;
            }
            if (doFunction && typeof(doFunction) === "function") {
                return doFunction(input) ? true : false;
            }
            else {
                this.errorMessage = "验证方法(" + this.func + ")无效";
                return false;
            }
        }
        return false;
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章