formik-validator-zod
Version:
Helper to simplify validating Formik values with Zod
20 lines (19 loc) • 606 B
JavaScript
import merge from 'deepmerge';
/**
* Allows you to easily use Zod schemas with the <Formik /> component `validate`
* prop.
*
* ```js
* <Formik {...} validate={withZodSchema(yourSchema)}>
* ```
*/
export const withZodSchema = (schema, params) => (values) => {
const result = schema.safeParse(values, params);
if (result.success)
return {};
return result.error.issues.reduce((acc, curr) => {
return merge(acc, curr.path.reduceRight((errors, pathSegment) => ({
[pathSegment]: !Object.keys(errors).length ? curr.message : errors,
}), {}));
}, {});
};