@hookform/resolvers
Version:
React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype and Typanion
47 lines (39 loc) • 1.16 kB
text/typescript
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: {} };
};