-
Notifications
You must be signed in to change notification settings - Fork 1
/
runkit.js
123 lines (117 loc) · 2.62 KB
/
runkit.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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const {
array,
boolean,
date,
email,
exact,
integer,
matches,
max,
maxDate,
min,
minDate,
number,
object,
oneOf,
required,
string,
url,
valid,
invalid,
} = require('validator-fns');
const ONE_DAY = 1000 * 60 * 60 * 24;
const TEN_DAYS = ONE_DAY * 10;
const now = new Date();
const tenDaysFromNow = new Date(now.getTime() + TEN_DAYS);
const customValidator = (value, field) => {
if (value === 'hello') {
return valid({ value, field });
}
return invalid({
message: 'Must be "hello".',
value,
field,
});
};
const validate = object({
firstName: string(
{ default: '', trim: true },
required('First name is required.'),
),
emailAddress: string(
required('Email address is required.'),
email('Must be a valid email address.'),
),
age: number(
{ round: 'floor' },
required('Age is required.'),
integer('Age must be a whole number.'),
min(18, 'Must be at least {min} years old.'),
),
homepage: string(url('Must be a valid URL.', ['http:', 'https:'])),
fruit: string(
{ default: 'apple' },
oneOf(
['apple', 'orange', 'banana'],
({ values }) => `Must be ${values[0]}, ${values[1]} or ${values[2]}.`,
),
),
favoriteCarMakers: array(
{ default: [] },
string(
required('Car brand is required.'),
oneOf(
[
'BMW',
'Ferrari',
'Fiat',
'Ford',
'Honda',
'Kia',
'Mercedes',
'Subaru',
'Tesla',
'Toyota',
'Volvo',
],
'Must be a known car brand.',
),
),
min(2, 'Must pick at least two.'),
max(4, 'Must pick at most four.'),
),
startDate: date(
minDate(now, 'Must be on or after today.'),
maxDate(tenDaysFromNow, 'Must be at most ten days from now.'),
),
optIn: boolean(required('Must decide to opt in or out.')),
notRobot: number(
required('Must enter the correct answer.'),
exact(42, 'This is the answer.'),
),
postalCode: string(matches(/^\d{5}$/, 'Must be a five-digit number.')),
custom: customValidator,
});
// Later...
(async () => {
const result = await validate({
age: 20,
custom: 'hello',
emailAddress: 'foo@example.com',
favoriteCarMakers: ['Ferrari', 'Tesla'],
firstName: 'Bob',
fruit: 'apple',
homepage: 'https://www.example.com',
notRobot: 42,
optIn: false,
postalCode: '12345',
startDate: new Date(),
});
if (result.state === 'valid') {
// Do something with the parsed values
console.log(result.value);
} else {
// Handle and display errors
console.error(result.errors);
}
})();