-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (74 loc) · 2.36 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
const regExp = {
email: !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
alphanumeric: /^[a-zA-Z0-9\s]{0,255}$/
};
module.exports = rules => {
return {
validate: (params, path, next) => {
let rule = rules;
if (path && path.trim() !== "") {
let newPath = path.split(".");
newPath.map(p => {
if (rule && rule[p]) rule = rule[p];
else rule = undefined;
return p;
});
}
if (rule instanceof Object) {
let errors = {};
for (let i in rule) {
errors[i] = {};
//Empty
if (rule[i].required && !params[i])
errors[i].required =
typeof rule[i].required === "string"
? rule[i].required
: "This field is required";
if (params[i]) {
//Email
if (rule[i].email && new RegExp(regExp.email).test(params[i]))
errors[i].email =
typeof rule[i].email === "string"
? rule[i].email
: "This field must be email";
//Array
if (rule[i].array && !Array.isArray(params[i])) {
errors[i].array =
typeof rule[i].array === "string"
? rule[i].array
: "This field must be array";
}
//String
if (
rule[i].string &&
!new RegExp(regExp.alphanumeric).test(params[i])
)
errors[i].string =
typeof rule[i].array === "string"
? rule[i].string
: "This field must be string";
//Max length
if (
rule[i].maxLength &&
params[i].toString().length > rule[i].maxLength
)
errors[i].maxLength = `Max length must be less than ${
rule[i].maxLength
}`;
//Min length
if (
rule[i].minLength &&
params[i].toString().length < rule[i].minLength
)
errors[i].minLength = `Min length must be greater than ${
rule[i].minLength
}`;
}
if (!Object.keys(errors[i]).length) delete errors[i];
}
if (!Object.keys(errors).length) next({ errors: undefined });
else next({ errors });
}
}
};
};