-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
nope.ts
46 lines (39 loc) 路 1.13 KB
/
nope.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
import type {FieldError, FieldErrors} from 'react-hook-form';
import { toNestError, validateFieldsNatively } from '@hookform/resolvers';
import type { ShapeErrors } from 'nope-validator/lib/cjs/types';
import type { Resolver } from './types';
const parseErrors = (
errors: ShapeErrors,
parsedErrors: FieldErrors = {},
path = '',
) => {
return Object.keys(errors).reduce((acc, key) => {
const _path = path ? `${path}.${key}` : key;
const error = errors[key];
if (typeof error === 'string') {
acc[_path] = {
message: error,
} as FieldError;
} else {
parseErrors(error, acc, _path);
}
return acc;
}, parsedErrors);
};
export const nopeResolver: Resolver =
(
schema,
schemaOptions = {
abortEarly: false,
},
) =>
(values, context, options) => {
const result = schema.validate(values, context, schemaOptions) as
| ShapeErrors
| undefined;
if (result) {
return { values: {}, errors: toNestError(parseErrors(result), options) };
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return { values, errors: {} };
};