-
Notifications
You must be signed in to change notification settings - Fork 6
/
validator1.0.js
713 lines (634 loc) · 25.6 KB
/
validator1.0.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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*
*validator.js 表单验证器
*@author:maxiupeng
*@date:2013-8-1
*/
define("Validator",function(require,exports,module){
require("jquery");
var VldRulesLib = require("VldRulesLib");
var limiter = require("limiter");
// / *获取光标位置插件 */
// $.fn.extend({
// position:function( value ){
// var elem = this[0];
// if (elem&&(elem.tagName=="TEXTAREA"||elem.type.toLowerCase()=="text")) {
// if($.browser.msie){
// var rng;
// if(elem.tagName == "TEXTAREA"){
// rng = event.srcElement.createTextRange();
// rng.moveToPoint(event.x,event.y);
// }else{
// rng = document.selection.createRange();
// }
// if( value === undefined ){
// rng.moveStart("character",-event.srcElement.value.length);
// return rng.text.length;
// }else if(typeof value === "number" ){
// var index=this.position();
// index>value?( rng.moveEnd("character",value-index)):(rng.moveStart("character",value-index))
// rng.select();
// }
// }else{
// if( value === undefined ){
// return elem.selectionStart;
// }else if(typeof value === "number" ){
// elem.selectionEnd = value;
// elem.selectionStart = value;
// }
// }
// }else{
// if( value === undefined )
// return undefined;
// }
// }
// })
var CHECK_INTERVAL = 100;
/* for debug,使用delegate还是直接绑定,有待商议 */
var delegate = true;
/* Validator命名空间 */
$.Validator = {};
/* 默认参数 */
$.Validator.defaults = {
vldOnclick: null, //type:$selector或$元素,点击某个button时验证
vldOnBlur: false, //元素失去焦点时验证
vldOnEnter: false, //input中按下enter时验证
checkOnError: true, //当前input内的数据不合法时自动验证数据
timer: true, //是否使用定时器验证,若否,使用keydown和onpaste代替
errorFiled: null, //集中显示错误信息的区域。
errorClass: "", //错误时input标签应用的css样式
errorLocClass: "", //错误时错误提示标签应用的样式,如show
errTipTpl: "<div class='errorTip' id='{{id}}' style='z-index:{{zindex}};"
+ "position:absolute;'>{{message}}</div>", //错误Tip模板,三个参数
tipDir: "right", //错误tip的显示位置,可选up,down left,right,关闭tip的话设置为false
tipOffset: null, //错误tip显示位置的偏移量,需要包含left和top
defaultMsg: "输入有误,请重新输入", //默认的错误提示信息
trigger: null, //验证触发器,数组类型,每个元素包括元素ID和事件名称
parent: "body" //父节点$selector,为空的话自动指定为body
}
/*
* validator 定义
* @param:validations {array} 应用到当前form中所有field的规则
* eg:[{
field:'userName',
rule:'required',
msg:'userName is required!',
errorLoc:'error_username',
dynamicVld:true
},{
...
}]
* @param:opts {object} 选项
*/
$.Validator.validator = function(validations, opts) {
if (!validations || !validations.length) return true;
this.opts = $.extend({}, $.Validator.defaults, opts);
this.errorMsg = {}; //集中显示的错误信息
this.hasRel = false; //各个field之间是否存在关联性
this.relations = {}; //储存各field之间的关联
//this._this = this;
this.dynamicVlds = []; //需要动态验证的validation列表
this.validations = validations;
this._init();
};
var Validator = $.Validator.validator;
/*
* 启动
*/
Validator.prototype._init = function() {
/* 映射实例变量为局部变量 */
var opts = this.opts;
var errorMsg = this.errorMsg;
var relations = this.relations;
var dynamicVlds = this.dynamicVlds;
var validations = this.validations;
var _this = this;
/* 设置$button */
opts.$button = $(opts.vldOnclick);
opts.$errorField = $(opts.errorField);
opts.$parent = $(opts.parent);
/* jQuery元素拆分 */
for(var i = 0; i < validations.length; i++){
if(validations[i].field.constructor == jQuery && validations[i].field.length > 1){
for(var j = 0; j < validations[i].field.length; j++){
// var vld = $.extend({},validations[i]);
// if(!validations[i].field[j].getAttribute("id")){
// validations[i].field[j].setAttribute("id",$.Validator.randomString(10));
// }
//vld.field = $(validations[i].field.selector + "#" + validations[i].field[j].getAttribute("id"));
validations.push(vld);
}
validations.shift(i);
}
}
/* 设置limiter、passed属性、hasRel属性、$el、$errorLoc、id、动态验证 */
for (var i = 0; i < validations.length; i++) {
validations[i].passed = true;
/* 设置$el */
if(validations[i].field.constructor == jQuery){
validations[i].$el = validations[i].field;
validations[i].randomId = $.Validator.randomString(10);
} else {
validations[i].$el = $("#" + validations[i].field);
validations[i].randomId = $.Validator.randomString(10);
}
if(!validations[i].$el.attr("id")){
validations[i].$el.attr("id", validations[i].randomId);
}
/* 设置$errorLoc */
validations[i].$errorLoc = $(validations[i].errorLoc);
/*关联检查功能,暂不可用
if (validations[i].rule.constructor == RegExp || (typeof validations[i].rule) == "function") {
} else if (validations[i].rule.indexOf("#") != -1) {
hasRel = true; //关联检查功能没有开启
}
//*/
if (validations[i].limiter) {
validations[i].$el.limiter(validations[i].limiter);
}
if(validations[i].dynamicVld){
dynamicVlds.push(validations[i]);
}
}
/* 绑定button的onclick */
if (opts.$button) {
opts.$button.bind('click', function(){
_this.validateAll()
});
}
/* 绑定input的onblur和回车键 */
if (opts.vldOnBlur || opts.vldOnEnter) {
for (var i = 0; i < validations.length; i++) {
if (opts.vldOnBlur) {
opts.$parent.delegate(validations[i].$el.selector, "blur", {
index: i,
field: validations[i].field
}, function(e){
_this.check(e.data.index);
});
}
if (opts.vldOnEnter) {
opts.$parent.delegate(validations[i].$el.selector, "keyup", {
index: i,
field: validations[i].field
}, function(e){
_this.onEnterHandler(e);
});
}
}
}
/* 设置自定义的触发器 */
if(opts.trigger){
for(var i = 0; i < opts.trigger.length; i++){
$(opts.trigger[i].elm).bind(opts.trigger[i].event,function(){
_this.validateAll()
});
}
}
/* 设置定时器和动态验证 */
if (opts.timer) {
//动态验证的定时器
if (dynamicVlds.length != 0) {
setInterval(function() {
for (var i = 0; i < dynamicVlds.length; i++) {
_this.dynamicCheck(dynamicVlds[i]);
}
}, CHECK_INTERVAL);
}
//出错时检验的定时器
if (opts.checkOnError) {
setInterval(function() {
for (var i = 0; i < validations.length; i++) {
if (validations[i].onError) { //onError专用于定时验证,不用passed是为了焦点不离开输入框时不取消定时器
if (_this.hasRel) {
_this.validateRel(validations[i]);
} else {
_this.validate(validations[i]);
}
}
}
}, CHECK_INTERVAL);
}
} else { //keydown和paste代替timer
for (var i = 0; i < validations.length; i++) {
if(validations[i].dynamicVld){
_this.initDynamicVld(validations[i]);
}
}
}
}
/*
* 初始化动态验证
*/
Validator.prototype.initDynamicVld = function(vld){
var _this = this;
if($.browser.msie){//IE
if(delegate){
//delegate
_this.opts.$parent.delegate(vld.$el.selector, "keydown", {vld: vld}, function(e) {
setTimeout(function() {
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
} else {
//on
vld.$el.on("keydown", {vld: vld}, function(e) {
setTimeout(function() {
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
}
} else {//非IE
if(delegate){
//delegate
_this.opts.$parent.delegate(vld.$el.selector, "input", {vld: vld}, function(e) {
setTimeout(function() {
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
} else {
//on
vld.$el.on("input", {vld: vld}, function(e) {
setTimeout(function() {
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
}
}
if(delegate){
//delegate
_this.opts.$parent.delegate(vld.$el.selector, "paste", {vld: vld}, function(e){
setTimeout(function(){
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
} else {
//on
vld.$el.on("paste", {vld: vld}, function(e){
setTimeout(function(){
// _this.dynamicCheck(_this.getValidation(e.target.id));
_this.dynamicCheck(e.data.vld);
}, 0);
});
}
}
/*
* 动态验证,方便callee识别
*/
Validator.prototype.dynamicCheck = function(vld){
this.validate(vld);
}
/*
* 用于绑定单个input的blur、change事件
*/
Validator.prototype.check = function(index) {
if(this.validations[index].onError){
this.validations[index].onError = false;
}
if (this.hasRel == false) {
return this.validate(this.validations[index]);
} else {
return this.validateRel(this.validations[index]);
}
}
/*
* onEnter handler
*/
Validator.prototype.onEnterHandler = function(e) {
if (e.keyCode == 13) {
return this.check(e.data.index);
}
}
/*
* 验证是否通过
*/
Validator.prototype.isPassed = function() {
for (var i = 0; i < this.validations.length; i++) {
if (!this.validations[i].passed) {
return false;
}
}
return true;
}
/*
* 验证结果列表
*/
Validator.prototype.results = function(){
return $.map(this.validations,function(val,index){
return {
field: val.field,
passed: val.passed
}
});
}
/*
* 验证全部field
*/
Validator.prototype.validateAll = function() {
var validations = this.validations;
var flag = true;
for (var i = 0; i < validations.length; i++) {
var result = this.validate(validations[i]);
flag = result == false ? false : flag;
}
//第一个错误标签获得焦点
if(!flag){
for (var i = 0; i < validations.length; i++) {
if (validations[i].passed == false) {
validations[i].$el.focus();
return false;
}
}
}
return flag;
}
/*
* 验证与某个field相关联的所有field
* @param validation {object} 目标验证规则,通过此validation.field指定目标field
*/
Validator.prototype.validateRel = function(validation) {
// 暂时不可用
/*
if (!relations[validation.field]) { //创建关系数组
relations[validation.field] = [validation];
for (var i = 0; i < validations.length; i++) {
if (validations[i].rule.constructor != RegExp && (typeof validations[i].rule) != "function" && validations[i].rule.indexOf("#" + validation.field) != -1) {
relations[validation.field].push(validations[i]);
}
}
}
var result = true;
for (var j = 0; j < relations[validation.field].length; j++) {
var result = validate(relations[validation.field][j]) == false ? false : result;
}
return result;
// */
}
/*
* 验证单个field
* @param validation {object} 验证规则
*/
Validator.prototype.validate = function(validation) {
/* 映射实例变量为局部变量 */
var opts = this.opts;
var errorMsg = this.errorMsg;
var relations = this.relations;
var dynamicVlds = this.dynamicVlds;
var validations = this.validations;
var _this = this;
var field = validation.field;
var randomId = validation.randomId;
var msg = validation.msg ? validation.msg : opts.defaultMsg;
var errorLoc = validation.errorLoc;
var $el = validation.$el;
var input = validation.$el[0];
var value = input.value;
var offsetLeft = validation.tipOffset && validation.tipOffset.left ? validation.tipOffset.left : 0;
var offsetTop = validation.tipOffset && validation.tipOffset.top ? validation.tipOffset.top : 0;
var tipDir = validation.tipDir;
//自定义函数验证
if (typeof validation.rule == "function") {
var result = validation.rule();
if (result) {
ok();
} else {
error();
}
return result;
}
//正则表达式验证
if (validation.rule.constructor == RegExp) {
var result = validation.rule.test(value);
validation.rule.lastIndex = 0;
if (result) {
ok();
} else {
error();
}
return result;
}
//普通验证
var rule = validation.rule;
if(rule.indexOf("#") != -1){
rule = rule.replace(/#[a-zA-Z0-9_]+/ig,function(val,index,original){
return $(val)[0].value + " ";
});
}
if(arguments.callee.caller == _this.dynamicCheck){
var result = VldRulesLib.validate(value, rule, "", msg, ok, error);
if(!result.result){
input.value = result.revisedVal;
}
}else{
VldRulesLib.validate(value, rule, "", msg, ok, error);
}
//验证成功后执行的操作
function ok() {
validation.passed = true;
if (errorLoc) {
validation.$errorLoc.html("");
if(opts.errorLocClass){
validation.$errorLoc.removeClass(opts.errorLocClass);
}else{
validation.$errorLoc.hide();
}
}
if (tipDir || opts.tipDir) {
$("#" + randomId + "_errTip").remove();
}
errorMsg[randomId] = "";
$el.removeClass(opts.errorClass);
_this.showInErrorField();
}
//验证失败后执行的操作
function error() {
validation.passed = false;
validation.onError = true; //在onblur中设置
if (errorLoc) {
validation.$errorLoc.html(msg);
if(opts.errorLocClass){
validation.$errorLoc.addClass(opts.errorLocClass);
}else{
validation.$errorLoc.show();
}
} else {
errorMsg[randomId] = msg;
}
$el.addClass(opts.errorClass);
if(opts.checkOnError && !opts.timer && !validation.binded){
validation.binded = true;
if($.browser.msie){//IE
if(delegate){
//delegate
opts.$parent.delegate($el.selector, "keydown", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
} else {
//on
$el.on("keydown", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
}
} else {//非IE
if(delegate){
//delegate
opts.$parent.delegate($el.selector, "input", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
} else {
//on
$el.on("input", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
}
}
if(delegate){
//delegate
opts.$parent.delegate($el.selector, "paste", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
} else {
//on
$el.on("paste", {vld: validation}, function(e) {
setTimeout(function() {
_this.validate(e.data.vld);
}, 0);
});
}
}
if (tipDir || opts.tipDir) {
$("#" + randomId + "_errTip").remove();
var errTip = $(opts.errTipTpl.replace("{{id}}",randomId + "_errTip")
.replace("{{zindex}}",$.Validator.getZIndex($el))
.replace("{{message}}",msg));
opts.$parent.append(errTip);
$.Validator.setTipLoc($el, errTip, tipDir, offsetLeft, offsetTop, opts);
}
_this.showInErrorField();
}
}
/*
* 集中显示错误信息
*/
Validator.prototype.showInErrorField = function() {
var errorMsg = this.errorMsg;
var opts = this.opts;
var msg = "";
for (var key in errorMsg) {
if (errorMsg[key] != "") {
msg += errorMsg[key];
msg += "<br/>";
}
}
if (opts.errorField) {
opts.$errorField.html(msg);
}
}
/*
* 获取元素位置
* @param elmId {string} 元素id
* @return result {object} 包含left,top,width,height
*/
$.Validator.getElmLoc = function($el) {
var result = {};
var elm = $el;
// result["left"] = elm[0].offsetLeft;
// result["top"] = elm[0].offsetTop;
// result["width"] = elm[0].offsetWidth;
// result["height"] = elm[0].offsetHeight;
//通过jQuery获取的有问题,宽度4个像素偏差,高度6个像素偏差
result["left"] = elm.offset().left;
result["top"] = elm.offset().top;
result["width"] = elm.width()+4;
result["height"] = elm.height()+6;
return result;
}
/*
* 设置error tip的位置
* @param:elmId {string} 目标input的ID
* @param:tip {$obj} 提示tip的$元素
* @param:tipDir {string} tip位置,up,down,left,right之一
* @param:left {number} 单个tip标签的左侧偏移量
* @param:top {number} 单个tip标签的上方偏移量
*/
$.Validator.setTipLoc = function($el, tip, tipDir, left, top, opts) {
if(opts == null||opts == undefined){
opts = {
tipDir:null,
tipOffset:null
};
}
if (!opts.tipDir && !tipDir) return;
var elmLoc = $.Validator.getElmLoc($el);
var tipWidth = tip[0].offsetWidth;
var tipHeight = tip[0].offsetHeight;
var result = {};
var offsetTop = (opts.tipOffset && opts.tipOffset.top ? opts.tipOffset.top : 0) + (top ? top : 0);
var offsetLeft = (opts.tipOffset && opts.tipOffset.left ? opts.tipOffset.left : 0) + (left ? left : 0);
var dir = tipDir ? tipDir : opts.tipDir;
if (dir == "up") {
result["top"] = elmLoc["top"] - tipHeight + offsetTop;
result["left"] = elmLoc["left"] + offsetLeft;
} else if (dir == "left") {
result["top"] = elmLoc["top"] + (elmLoc["height"] - tipHeight) / 2 + offsetTop;
result["left"] = elmLoc["left"] - tipWidth + offsetLeft;
} else if (dir == "down") {
result["top"] = elmLoc["top"] + elmLoc["height"] + offsetTop;
result["left"] = elmLoc["left"] + offsetLeft;
} else if (dir == "right") {
result["top"] = elmLoc["top"] + (elmLoc["height"] - tipHeight) / 2 + offsetTop;
result["left"] = elmLoc["left"] + elmLoc["width"] + offsetLeft;
} else {
console.log("tipDir设置错误!")
return;
}
tip.offset(result);
}
//获取元素的z-index
$.Validator.getZIndex = function($elm){
if($elm[0].tagName == "BODY"){
return 1;
}
var z = $elm.css("z-index");
if(z == "auto") {
z = $.Validator.getZIndex($elm.parent());
}
return z;
}
$.Validator.randomString = function(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
/**********************************************************************/
/*
* 单个input验证
*/
$.fn.validator = function(validation){
validation.field = this;
var vld = new $.Validator.validator(validation,validation);
return this;
};
module.exports = Validator;
window.Validator = Validator;
});