/
validate.ts
354 lines (315 loc) · 9.41 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import { RuleContainer } from './extend';
import { isObject, isNullOrUndefined, normalizeRules, isEmptyArray, interpolate } from './utils';
import { ValidationResult, ValidationRuleSchema, ValidationMessageTemplate, RuleParamConfig } from './types';
import { getConfig } from './config';
interface FieldContext {
name: string;
rules: Record<string, any[]>;
bails: boolean;
skipIfEmpty: boolean;
forceRequired: boolean;
crossTable: Record<string, any>;
names: Record<string, string>;
customMessages: Record<string, string>;
}
interface ValidationOptions {
name?: string;
values?: Record<string, any>;
names?: Record<string, string>;
bails?: boolean;
skipIfEmpty?: boolean;
isInitial?: boolean;
customMessages?: Record<string, string>;
}
/**
* Validates a value against the rules.
*/
export async function validate(
value: any,
rules: string | Record<string, any>,
options: ValidationOptions = {}
): Promise<ValidationResult> {
const shouldBail = options && options.bails;
const skipIfEmpty = options && options.skipIfEmpty;
const field: FieldContext = {
name: (options && options.name) || '{field}',
rules: normalizeRules(rules),
bails: isNullOrUndefined(shouldBail) ? true : shouldBail,
skipIfEmpty: isNullOrUndefined(skipIfEmpty) ? true : skipIfEmpty,
forceRequired: false,
crossTable: (options && options.values) || {},
names: (options && options.names) || {},
customMessages: (options && options.customMessages) || {}
};
const result = await _validate(field, value, options);
const errors: string[] = [];
const ruleMap: Record<string, string> = {};
result.errors.forEach(e => {
errors.push(e.msg);
ruleMap[e.rule] = e.msg;
});
return {
valid: result.valid,
errors,
failedRules: ruleMap
};
}
/**
* Starts the validation process.
*/
async function _validate(field: FieldContext, value: any, { isInitial = false } = {}) {
const { shouldSkip, errors } = await _shouldSkip(field, value);
if (shouldSkip) {
return {
valid: !errors.length,
errors
};
}
// Filter out non-require rules since we already checked them.
const rules = Object.keys(field.rules).filter(rule => !RuleContainer.isRequireRule(rule));
const length = rules.length;
for (let i = 0; i < length; i++) {
if (isInitial && RuleContainer.isLazy(rules[i])) {
continue;
}
const rule = rules[i];
const result = await _test(field, value, {
name: rule,
params: field.rules[rule]
});
if (!result.valid && result.error) {
errors.push(result.error);
if (field.bails) {
return {
valid: false,
errors
};
}
}
}
return {
valid: !errors.length,
errors
};
}
async function _shouldSkip(field: FieldContext, value: any) {
const requireRules = Object.keys(field.rules).filter(RuleContainer.isRequireRule);
const length = requireRules.length;
const errors: ReturnType<typeof _generateFieldError>[] = [];
const isEmpty = isNullOrUndefined(value) || value === '' || isEmptyArray(value);
const isEmptyAndOptional = isEmpty && field.skipIfEmpty;
let isRequired = false;
for (let i = 0; i < length; i++) {
const rule = requireRules[i];
const result = await _test(field, value, {
name: rule,
params: field.rules[rule]
});
if (!isObject(result)) {
throw new Error('Require rules has to return an object (see docs)');
}
if (result.required) {
isRequired = true;
}
if (!result.valid && result.error) {
errors.push(result.error);
// Exit early as the field is required and failed validation.
if (field.bails) {
return {
shouldSkip: true,
errors
};
}
}
}
if (isEmpty && !isRequired && !field.skipIfEmpty) {
return {
shouldSkip: false,
errors
};
}
// field is configured to run through the pipeline regardless
if (!field.bails && !isEmptyAndOptional) {
return {
shouldSkip: false,
errors
};
}
// skip if the field is not required and has an empty value.
return {
shouldSkip: !isRequired && isEmpty,
errors
};
}
/**
* Tests a single input value against a rule.
*/
async function _test(field: FieldContext, value: any, rule: { name: string; params: any[] | object }) {
const ruleSchema = RuleContainer.getRuleDefinition(rule.name);
if (!ruleSchema || !ruleSchema.validate) {
throw new Error(`No such validator '${rule.name}' exists.`);
}
// build params
const params = _buildParams(rule.params, ruleSchema.params, field.crossTable);
const normalizedValue = ruleSchema.castValue ? ruleSchema.castValue(value) : value;
let result = await ruleSchema.validate(normalizedValue, params);
if (typeof result === 'string') {
const values = {
...(params || {}),
_field_: field.name,
_value_: value,
_rule_: rule.name
};
return {
valid: false,
error: { rule: rule.name, msg: interpolate(result, values) }
};
}
if (!isObject(result)) {
result = { valid: result, data: {} };
}
return {
valid: result.valid,
required: result.required,
data: result.data || {},
error: result.valid ? undefined : _generateFieldError(field, value, ruleSchema, rule.name, params, result.data)
};
}
/**
* Generates error messages.
*/
function _generateFieldError(
field: FieldContext,
value: any,
ruleSchema: ValidationRuleSchema,
ruleName: string,
params: Record<string, any>,
data?: Record<string, any>
) {
const values = {
...(params || {}),
...(data || {}),
_field_: field.name,
_value_: value,
_rule_: ruleName,
..._getTargetNames(field, ruleSchema, ruleName)
};
if (
Object.prototype.hasOwnProperty.call(field.customMessages, ruleName) &&
typeof field.customMessages[ruleName] === 'string'
) {
return {
msg: _normalizeMessage(field.customMessages[ruleName], field.name, values),
rule: ruleName
};
}
if (ruleSchema.message) {
return {
msg: _normalizeMessage(ruleSchema.message, field.name, values),
rule: ruleName
};
}
return {
msg: _normalizeMessage(getConfig().defaultMessage, field.name, values),
rule: ruleName
};
}
function _getTargetNames(
field: FieldContext,
ruleSchema: ValidationRuleSchema,
ruleName: string
): Record<string, string> {
if (ruleSchema.params) {
const numTargets = ruleSchema.params.filter(param => (param as RuleParamConfig).isTarget).length;
if (numTargets > 0) {
const names: Record<string, string> = {};
for (let index = 0; index < ruleSchema.params.length; index++) {
const param: RuleParamConfig = ruleSchema.params[index] as RuleParamConfig;
if (param.isTarget) {
const key = field.rules[ruleName][index];
const name = field.names[key] || key;
if (numTargets === 1) {
names._target_ = name;
break;
} else {
names[`_${param.name}Target_`] = name;
}
}
}
return names;
}
}
return {};
}
function _normalizeMessage(template: ValidationMessageTemplate, field: string, values: Record<string, any>) {
if (typeof template === 'function') {
return template(field, values);
}
return interpolate(template, { ...values, _field_: field });
}
function _buildParams(
provided: any[] | Record<string, any>,
defined: RuleParamConfig[] | undefined,
crossTable: Record<string, any>
) {
const params: Record<string, any> = {};
if (!defined && !Array.isArray(provided)) {
throw new Error('You provided an object params to a rule that has no defined schema.');
}
// Rule probably uses an array for their args, keep it as is.
if (Array.isArray(provided) && !defined) {
return provided;
}
let definedRules: RuleParamConfig[];
// collect the params schema.
if (!defined || (defined.length < provided.length && Array.isArray(provided))) {
let lastDefinedParam: RuleParamConfig;
// collect any additional parameters in the last item.
definedRules = provided.map((_: any, idx: number) => {
let param = defined && defined[idx];
lastDefinedParam = param || lastDefinedParam;
if (!param) {
param = lastDefinedParam;
}
return param;
});
} else {
definedRules = defined;
}
// Match the provided array length with a temporary schema.
for (let i = 0; i < definedRules.length; i++) {
const options = definedRules[i];
let value = options.default;
// if the provided is an array, map element value.
if (Array.isArray(provided)) {
if (i in provided) {
value = provided[i];
}
} else {
// If the param exists in the provided object.
if (options.name in provided) {
value = provided[options.name];
// if the provided is the first param value.
} else if (definedRules.length === 1) {
value = provided;
}
}
// if the param is a target, resolve the target value.
if (options.isTarget) {
value = crossTable[value];
}
// If there is a transformer defined.
if (options.cast) {
value = options.cast(value);
}
// already been set, probably multiple values.
if (params[options.name]) {
params[options.name] = Array.isArray(params[options.name]) ? params[options.name] : [params[options.name]];
params[options.name].push(value);
} else {
// set the value.
params[options.name] = value;
}
}
return params;
}