-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathvalidate.ts
329 lines (300 loc) · 8.85 KB
/
validate.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import lodashMemoize from 'lodash/memoize';
/* eslint-disable no-underscore-dangle */
/* @link http://stackoverflow.com/questions/46155/validate-email-address-in-javascript */
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; // eslint-disable-line no-useless-escape
const isEmpty = (value: any) =>
typeof value === 'undefined' ||
value === null ||
value === '' ||
(Array.isArray(value) && value.length === 0);
export interface ValidationErrorMessageWithArgs {
message: string;
args: {
[key: string]: ValidationErrorMessageWithArgs | any;
};
}
export type ValidationErrorMessage = string | ValidationErrorMessageWithArgs;
export type Validator = (
value: any,
values: any,
props: any
) =>
| ValidationErrorMessage
| null
| undefined
| Promise<ValidationErrorMessage | null | undefined>;
// type predicate, see https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
function isValidationErrorMessageWithArgs(
error: ReturnType<Validator>
): error is ValidationErrorMessageWithArgs {
return error ? error.hasOwnProperty('message') : false;
}
interface MessageFuncParams {
args: any;
value: any;
values: any;
}
type MessageFunc = (params: MessageFuncParams) => ValidationErrorMessage;
const getMessage = (
message: string | MessageFunc,
messageArgs: any,
value: any,
values: any
) =>
typeof message === 'function'
? message({
args: messageArgs,
value,
values,
})
: messageArgs
? {
message,
args: messageArgs,
}
: message;
type Memoize = <T extends (...args: any[]) => any>(
func: T,
resolver?: (...args: any[]) => any
) => T;
// If we define validation functions directly in JSX, it will
// result in a new function at every render, and then trigger infinite re-render.
// Hence, we memoize every built-in validator to prevent a "Maximum call stack" error.
const memoize: Memoize = (fn: any) =>
lodashMemoize(fn, (...args) => JSON.stringify(args));
const isFunction = value => typeof value === 'function';
export const combine2Validators = (
validator1: Validator,
validator2: Validator
): Validator => {
return (value, values, meta) => {
const result1 = validator1(value, values, meta);
if (!result1) {
return validator2(value, values, meta);
}
if (
typeof result1 === 'string' ||
isValidationErrorMessageWithArgs(result1)
) {
return result1;
}
return result1.then(resolvedResult1 => {
if (!resolvedResult1) {
return validator2(value, values, meta);
}
return resolvedResult1;
});
};
};
// Compose multiple validators into a single one for use with react-hook-form
export const composeValidators = (...validators) => {
const allValidators = (Array.isArray(validators[0])
? validators[0]
: validators
).filter(isFunction) as Validator[];
return allValidators.reduce(combine2Validators, () => null);
};
// Compose multiple validators into a single one for use with react-hook-form
export const composeSyncValidators = (...validators) => (
value,
values,
meta
) => {
const allValidators = (Array.isArray(validators[0])
? validators[0]
: validators
).filter(isFunction) as Validator[];
for (const validator of allValidators) {
const error = validator(value, values, meta);
if (error) {
return error;
}
}
};
/**
* Required validator
*
* Returns an error if the value is null, undefined, or empty
*
* @param {string|Function} message
*
* @example
*
* const titleValidators = [required('The title is required')];
* <TextInput name="title" validate={titleValidators} />
*/
export const required = memoize((message = 'ra.validation.required') =>
Object.assign(
(value, values) =>
isEmpty(value)
? getMessage(message, undefined, value, values)
: undefined,
{ isRequired: true }
)
);
/**
* Minimum length validator
*
* Returns an error if the value has a length less than the parameter
*
* @param {integer} min
* @param {string|Function} message
*
* @example
*
* const passwordValidators = [minLength(10, 'Should be at least 10 characters')];
* <TextInput type="password" name="password" validate={passwordValidators} />
*/
export const minLength = memoize(
(min, message = 'ra.validation.minLength') => (value, values) =>
!isEmpty(value) && value.length < min
? getMessage(message, { min }, value, values)
: undefined
);
/**
* Maximum length validator
*
* Returns an error if the value has a length higher than the parameter
*
* @param {integer} max
* @param {string|Function} message
*
* @example
*
* const nameValidators = [maxLength(10, 'Should be at most 10 characters')];
* <TextInput name="name" validate={nameValidators} />
*/
export const maxLength = memoize(
(max, message = 'ra.validation.maxLength') => (value, values) =>
!isEmpty(value) && value.length > max
? getMessage(message, { max }, value, values)
: undefined
);
/**
* Minimum validator
*
* Returns an error if the value is less than the parameter
*
* @param {integer} min
* @param {string|Function} message
*
* @example
*
* const fooValidators = [minValue(5, 'Should be more than 5')];
* <NumberInput name="foo" validate={fooValidators} />
*/
export const minValue = memoize(
(min, message = 'ra.validation.minValue') => (value, values) =>
!isEmpty(value) && value < min
? getMessage(message, { min }, value, values)
: undefined
);
/**
* Maximum validator
*
* Returns an error if the value is higher than the parameter
*
* @param {integer} max
* @param {string|Function} message
*
* @example
*
* const fooValidators = [maxValue(10, 'Should be less than 10')];
* <NumberInput name="foo" validate={fooValidators} />
*/
export const maxValue = memoize(
(max, message = 'ra.validation.maxValue') => (value, values) =>
!isEmpty(value) && value > max
? getMessage(message, { max }, value, values)
: undefined
);
/**
* Number validator
*
* Returns an error if the value is not a number
*
* @param {string|Function} message
*
* @example
*
* const ageValidators = [number('Must be a number')];
* <TextInput name="age" validate={ageValidators} />
*/
export const number = memoize(
(message = 'ra.validation.number') => (value, values) =>
!isEmpty(value) && isNaN(Number(value))
? getMessage(message, undefined, value, values)
: undefined
);
/**
* Regular expression validator
*
* Returns an error if the value does not match the pattern given as parameter
*
* @param {RegExp} pattern
* @param {string|Function} message
*
* @example
*
* const zipValidators = [regex(/^\d{5}(?:[-\s]\d{4})?$/, 'Must be a zip code')];
* <TextInput name="zip" validate={zipValidators} />
*/
export const regex = lodashMemoize(
(pattern, message = 'ra.validation.regex') => (value, values?) =>
!isEmpty(value) && typeof value === 'string' && !pattern.test(value)
? getMessage(message, { pattern }, value, values)
: undefined,
(pattern, message) => {
return pattern.toString() + message;
}
);
/**
* Email validator
*
* Returns an error if the value is not a valid email
*
* @param {string|Function} message
*
* @example
*
* const emailValidators = [email('Must be an email')];
* <TextInput name="email" validate={emailValidators} />
*/
export const email = memoize((message = 'ra.validation.email') =>
regex(EMAIL_REGEX, message)
);
const oneOfTypeMessage: MessageFunc = ({ args }) => ({
message: 'ra.validation.oneOf',
args,
});
/**
* Choices validator
*
* Returns an error if the value is not among the list passed as parameter
*
* @param {array} list
* @param {string|Function} message
*
* @example
*
* const genderValidators = [choices(['male', 'female'], 'Must be either Male or Female')];
* <TextInput name="gender" validate={genderValidators} />
*/
export const choices = memoize(
(list, message = oneOfTypeMessage) => (value, values) =>
!isEmpty(value) && list.indexOf(value) === -1
? getMessage(message, { list }, value, values)
: undefined
);
/**
* Given a validator, returns a boolean indicating whether the field is required or not.
*/
export const isRequired = validate => {
if (validate && validate.isRequired) {
return true;
}
if (Array.isArray(validate)) {
return !!validate.find(it => it.isRequired);
}
return false;
};