-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (90 loc) · 2.34 KB
/
index.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
"use strict";
var regexOptions,
lengthOptions
;
regexOptions = {
uppercase : '.*[A-Z]',
special : '.*[!@#$&*]',
digit : '.*[0-9]',
lowercase : '.*[a-z]',
upperLower : '.*[a-zA-Z]',
alphaNumeric : '.*[a-zA-Z0-9]'
};
lengthOptions = {
min : '.{n,}',
max : '.{0,n}',
range : '.{min,max}',
exact : '.{n}',
no_limit : '.*'
};
function create(options) {
var regex = '^';
for (var key in regexOptions) {
if (isNumber(options[key])) {
regex += '(?=' + regexOptions[key].repeat(options[key]) + ')';
}
}
if (isNumber(options.min) && isNumber(options.max)) {
regex += lengthOptions.range.replace('min', options.ran).replace('max', options.max);
} else if (isNumber(options.max)) {
regex += lengthOptions.max.replace('n', options.max);
} else if (isNumber(options.min)) {
regex += lengthOptions.min.replace('n', options.min);
} else if (isNumber(options.exact)) {
regex += lengthOptions.exact.replace('n', options.exact);
} else {
regex += lengthOptions.no_limit
}
regex += '$'
return regex;
}
function check(str, regex) {
if (typeof regex === 'object') {
regex = create(regex);
}
regex = new RegExp(regex);
return regex.test(str);
}
function checkError(str, options) {
var tempOption = {}
, optionLength = {
min : options.min,
max : options.max,
exact : options.exact
}
, returnObject = {}
, str = str || ''
;
for (var key in regexOptions) {
if (isNumber(options[key])) {
tempOption[key] = options[key];
returnObject[key] = check(str, tempOption);
delete tempOption[key];
}
}
for (key in optionLength) {
if (isNumber(optionLength[key])) {
tempOption[key] = optionLength[key];
returnObject[key] = check(str, tempOption);
delete tempOption[key]
}
}
return returnObject;
}
//************************
//*** Helper Functions ***
//************************
function isNumber(object) {
return typeof object === 'number';
}
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
//************************
//*** Module Export ******
//************************
module.exports = {
create : create,
check : check,
checkError : checkError
}