-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvalidators.js
78 lines (69 loc) · 1.89 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
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
const {
isAfter,
isBefore,
isCreditCard,
isUUID,
isURL,
isEmail,
isBase64,
isRFC3339,
isIP,
matches,
contains
} = require('validator')
const { length } = require('./utils')
// default formats, you can extend this in your code
const format2fun = {
email: isEmail,
base64: isBase64,
date: isRFC3339,
ipv4: x => isIP(x, 4),
ipv6: x => isIP(x, 6),
url: isURL,
uuid: isUUID,
futuredate: isAfter,
pastdate: isBefore,
creditcard: isCreditCard
}
// needs to be configured using format2fun
const formatValidator = format2fun => ({
format: fmtName => format2fun[fmtName]
})
const stringValidators = {
minLength: min => strOrArray => length(strOrArray) >= min,
maxLength: max => strOrArray => length(strOrArray) <= max,
startsWith: prefix => str => str != null && str.startsWith(prefix),
endsWith: suffix => str => str != null && str.endsWith(suffix),
contains: el => str => contains(str, el),
notContains: el => str => !contains(str, el),
pattern: pat => str => matches(str, pat),
differsFrom: argName => (value, queryArgs) => value !== queryArgs[argName]
}
const numericValidators = {
min: min => x => x >= min,
max: max => x => x <= max,
exclusiveMin: min => x => x > min,
exclusiveMax: max => x => x < max,
notEqual: neq => x => x !== neq
}
const defaultErrorMessageCallback = ({ argName, cName, cVal, data }) =>
`Constraint '${cName}:${cVal}' violated in field '${argName}'`
const defaultValidators = {
...formatValidator(format2fun),
...numericValidators,
...stringValidators
}
const createValidationCallback = validators => input => ({
...input,
result: validators[input.cName](input.cVal)(input.data)
})
module.exports = {
defaultValidators,
defaultValidationCallback: createValidationCallback(defaultValidators),
defaultErrorMessageCallback,
createValidationCallback,
stringValidators,
numericValidators,
formatValidator,
format2fun
}