validation.js
2.31 KB
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
var common = require('../../common');
var makeValidate = {
reg: function(val, reg) {
return reg.test(val);
},
minLength: function(val, l) {
return common.getStrLength(val) >= l;
},
maxLength: function(val, l) {
return common.getStrLength(val) <= l;
},
isNumber: function(val, bl) {
return bl && !isNaN(parseInt(val, 10));
},
necessary: function(val, bl) {
return bl && common.getStrLength(val) > 0;
},
addr: function(val) {
// 完整的地址应该是长度为三的数组
return val.split(',').length === 3;
}
};
function showMsg(obj) {
var text = obj.msg || '数据格式有问题,请检查';
var m = '<span class="error-msg validate-msg"><span class="iconfont"></span>' + text + '</span>';
var curMsg = $(obj.el).next('.validate-msg');
if (curMsg.length > 0) {
curMsg.remove();
}
if (obj.err) {
$(obj.el).after(m);
} else {
m = '<span class="correct-msg validate-msg"><span class="iconfont"></span>';
$(obj.el).after(m);
}
}
/*
* 根据conditions规则验证selector的值
* @param {String} selector jquery选择器
* @param {Object} conditions 验证对象
* @retrun {Boolen} true/false
*/
/*
* @example:
* validate.do('#user-name', {
* minLength: 3,
* reg: /\w/,
* necessary: true
* })
*/
function validate(selector, conditions) {
var pass = true;
var $el = $(selector);
var c;
for (c in conditions) {
if (makeValidate[c] && !makeValidate[c].call(null, $el.val(), conditions[c])) {
pass = false;
showMsg({
el: selector,
err: true,
msg: conditions.errMsg
});
return false;
} else if (c !== 'errMsg') {
showMsg({
el: selector
});
}
}
return pass;
}
function validateAddr(val, conditions) {
var pass = true;
if (makeValidate.addr(val)) {
showMsg({
el: conditions.el
});
} else {
pass = false;
showMsg({
el: conditions.el,
err: true,
msg: conditions.errMsg
});
}
return pass;
}
module.exports = {
start: validate,
addr: validateAddr
};