-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmultiple-validators.js
48 lines (36 loc) · 1.09 KB
/
multiple-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
// We could also define multiple validators,
// so that the code slices are more reusable
// Let's refractor the `PositiveNumber` with multiple validators
import {type} from 'skema'
// 1
// So that `isNumber` and `isPositive`
// could be used by other modules
export const isNumber = n => typeof n === 'number'
export const isPositive = n => n > 0
export const PositiveNumber = type({
// The property validate could also be an array of validators.
// The given value will be tested against the validator
// one by one.
// If passed the first validator,
// and it will be tested against the second one, and so on.
// Otherwise, the validation stops and throws
validate: [isNumber, isPositive]
})
PositiveNumber.from('1') // Error thrown
PositiveNumber.from(-1) // Error thrown
// 2
export const isNumberThrown = n => {
if (typeof n !== 'number') {
throw 'not a number'
}
return true
}
export const isPositiveThrown = n => {
if (n <= 0) {
throw 'must be positive'
}
return true
}
export const PositiveNumberVerbose = type({
validate: [isNumberThrown, isPositiveThrown]
})