-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (91 loc) · 2.16 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
// validation-helper.js
const validator = require('validator');
function isNullish(value) {
return (value === undefined || value === null);
}
function isBase32ApiKey(value) {
const test1 = /[a-zA-Z0-9]{28}/;
const test2 = /[a-zA-Z0-9]{7}-[a-zA-Z0-9]{7}-[a-zA-Z0-9]{7}-[a-zA-Z0-9]{7}/;
return (test1.test(value) || test2.test(value));
}
class Validator {
constructor() {}
validate(value, type, options) {
let test = true;
switch (type) {
case 'int':
case 'integer':
test = validator.isInt(value.toString(), options);
break;
case 'float':
test = validator.isFloat(value.toString(), options);
break;
case 'bool':
case 'boolean':
test = validator.isBoolean(value.toString());
break;
case 'email':
test = validator.isEmail(value.toString(), options);
break;
case 'currency':
test = validator.isCurrency(value.toString(), options);
break;
case 'uuid':
test = validator.isUUID(value.toString());
break;
case 'url':
test = validator.isURL(value.toString(), options);
break;
case 'fqdn':
test = validator.isFQDN(value.toString(), options);
break;
case 'apikey':
test = isBase32ApiKey(value.toString());
break;
case 'string':
case 'any':
default:
break;
}
return test;
}
convert(value, type) {
let out = value;
if (!isNullish(out)) {
switch (type) {
case 'int':
case 'integer':
out = parseInt(value);
break;
case 'float':
out = parseFloat(value);
break;
case 'bool':
case 'boolean':
out = this.strToBool(value);
break;
default:
break;
}
}
return out;
}
strToBool(str) {
switch (str.toString().toLowerCase()
.trim()) {
case 'true':
case 'yes':
case '1':
return true;
case 'false':
case 'no':
case '0':
case '':
case null:
return false;
default:
return false;
}
}
}
module.exports = new Validator();