-
Notifications
You must be signed in to change notification settings - Fork 0
/
validators.js
51 lines (49 loc) · 1.98 KB
/
validators.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
import validator from "validator";
import { EMAIL_REGEX } from "../../helpers";
export const validateAbilityData = (ability, value) => {
const errors = [];
if (ability.type === "number") {
if (!/^-?(\d)*\.?(\d)*$/.test(value)) {
errors.push("Not a valid number");
} else {
value = Number(value);
if (ability.maxValue && value > ability.maxValue) {
errors.push(`Maximum allowed value is ${ability.maxValue}`);
}
if (ability.minValue && value < ability.minValue) {
errors.push(`Minimum allowed value is ${ability.minValue}`);
}
if (ability.multipleOf && value % ability.multipleOf !== 0) {
errors.push(`Has to be multiple of ${ability.multipleOf}`);
}
}
} else if (ability.type === "string") {
value = value.toString();
if (ability.format === "date-time" && !validator.isISO8601(value)) {
errors.push("Not valid ISO8601 date-time");
} else if (ability.format === "email" && !EMAIL_REGEX.test(value)) {
errors.push("Not valid email");
} else if (
ability.format === "hostname" &&
!/^[a-z0-9]+([-.][a-z0-9]+)*\.[a-z]{2,}$/.test(value)
) {
errors.push("Not valid hostname");
} else if (ability.format === "ipv4" && !validator.isIP(value, 4)) {
errors.push("Not valid ipv4");
} else if (ability.format === "ipv6" && !validator.isIP(value, 6)) {
errors.push("Not valid ipv6");
} else if (ability.format === "uri" && !validator.isURL(value)) {
errors.push("Not valid uri");
}
if (ability.maxLength && value.length > ability.maxLength) {
errors.push(`Must have a max length of ${ability.maxLength}`);
}
if (ability.minLength && value.length < ability.minLength) {
errors.push(`Must have a min length of ${ability.minLength}`);
}
if (ability.pattern && !validator.matches(value, ability.pattern)) {
errors.push(`Must match with pattern ${ability.pattern}`);
}
}
return errors.length ? errors.join(". ") : null;
};