-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.ts
108 lines (92 loc) · 2.46 KB
/
validation.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
type TSource = { [key: string]: any }
type TResult = string|boolean
type TValue = string|number|boolean
type TValidator = (source: TSource) => TResult
type TModifyCreator = (argument: string | TValidator, error?: TResult) => TValidator
type TCompareCreator = (argument: string, value: TValue|RegExp, error?: TResult) => TValidator
type TSelectCreator = (argument: TValidator[], error?: TResult) => TValidator
const is: TModifyCreator = (argument, error = false) => (source) => {
switch(typeof argument) {
case 'function': {
return !!argument(source) ? true : error
}
case 'string':
case 'number': {
return !!source[argument] ? true : error
}
default: {
return error
}
}
}
const not: TModifyCreator = (argument, error = false) => (source) => {
// TODO
return false
}
const gt: TCompareCreator = (argument, value, error = false) => (source) => {
return source[argument] > value
? true
: error
}
const lt: TCompareCreator = (argument, value, error = false) => (source) => {
return source[argument] < value
? true
: error
}
const eq: TCompareCreator = (argument, value, error = false) => (source) => {
return source[argument] === value
? true
: error
}
// TODO
const reg: TCompareCreator = (argument, value: RegExp, error = false) => (source) => {
return false
}
const all: TSelectCreator = (argument = [], error = false) => (source) => {
const callback = argument.find(cb => {
return cb(source) !== true
})
const result = callback ? callback(source) : true
switch (typeof result) {
case 'string':
case 'boolean': {
return result
}
default: {
return error
}
}
}
const any: TSelectCreator = (argument = [], error = false) => (source) => {
const tests = argument
.map(cb => cb(source))
const success = tests
.find(res => res === true)
const failure = tests
.find(res => res !== true)
const result = success
? true
: failure || error
return result
}
const validator = (source: TSource, rule: TValidator, field?: string) => (value: TValue): TResult => {
return typeof field !== 'undefined'
? rule({ ...source, [field]: value })
: rule({ ...source })
}
const source = {
no_limit: true,
time_limit: 1200,
}
const test = any([
all([
gt('time_limit', 0, 'too low'),
lt('time_limit', 200, 'too high'),
]),
is('no_limit', 'not limited'),
])
const time_validator = validator(source, test, 'time_limit')
console.log(time_validator(300))
source.no_limit = false
console.log(time_validator(1500))
console.log(time_validator(150))