-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbasic-validation.js
51 lines (41 loc) · 999 Bytes
/
basic-validation.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 {type} from 'skema'
// 1
const TypeNumber = type({
// If the return value is
// - true: pass the validation
// - false: validation fails
validate: v => typeof v === 'number'
})
TypeNumber.from(1) // 1
TypeNumber.from('1')
// Error
// - code: 'VALIDATION_FAILS'
// ...
// 2
// You could just throw an error if something is wrong.
// With this mechanism,
// we could make our error reason verbose if necessary
const PositiveNumber = type({
validate (v) {
if (typeof v !== 'number') {
return false
}
if (v > 0) {
return true
}
// If the subject thrown is not an Error,
// an Error will be created based on the subject
throw 'must be positive'
}
})
PositiveNumber.from(1) // 1
PositiveNumber.from(-1) // Error thrown
// throw Error
// - code: 'CUSTOM_ERROR'
// - message: 'must be positive'
// 3
// Regular expression as a validator
const Alphabets = type({
validate: /^[a-z]+$/i
})
Alphabets.from('123') // Error thrown