password-check.js
1.75 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
'use strict';
var config = {
rules: [
{method: 'required', param: []},
{method: 'lte', param: [20]},
{method: 'gte', param: [6]},
{method: 'charLimit', param: []}
],
msgs: {
required: '由字母、数字组合,不能包含特殊字符',
lte: '长度须在6-20个字符之间',
gte: '长度须在6-20个字符之间',
charLimit: '密码须为字母和数字组合'
}
};
var validators = {
required: function(val) {
return !!val.length;
},
gte: function(val, param) {
return val.length >= param;
},
lte: function(val, param) {
return val.length <= param;
},
charLimit: function(val) {
return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(val);
}
};
function validate(val, callback) {
var rules = config.rules,
msgs = config.msgs,
i, ruleLen;
var name, param, errorMsg = '', pass = true;
// apple rule one by one;
for (i = 0, ruleLen = rules.length; i < ruleLen; i++) {
name = rules[i].method;
param = rules[i].param.concat();
param.unshift(val);
pass = validators[name].apply(this, param);
if (!pass) {
errorMsg = msgs[name];
break;
}
}
if (callback) {
pass ? callback({valid: true}) : callback({valid: false, msg: errorMsg}); // eslint-disable-line
}
return pass;
}
// test
/* eslint-disable */
// validate('1234567', function(result) {console.log(result)})
// validate('12345', function(result) {console.log(result)});
// validate('a'.repeat(21), function(result) {console.log(result)});
// validate('1abcdefg', function(result) {console.log(result)});
/* eslint-enable */
module.exports = validate;