Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save washingtonsoares/850ea7df48343ad7f6cc01229b83c708 to your computer and use it in GitHub Desktop.
Save washingtonsoares/850ea7df48343ad7f6cc01229b83c708 to your computer and use it in GitHub Desktop.
withZodSchema.ts
import type { ParseParams, ZodSchema } from "zod";
/**
* Allows you to easily use Zod schemas with the <Formik /> component `validate`
* prop.
*
* ```js
* <Formik {...} validate={withZodSchema(yourSchema)}>
* ```
*/
export const withZodSchema =
<T>(schema: ZodSchema<T>, params?: Partial<ParseParams>) =>
(values: T): Partial<T> => {
const result = schema.safeParse(values, params);
if (result.success) return {};
const errors = result.error.issues.reduce((acc, curr) => {
const key = curr.path.join(".");
return {
...acc,
[key]: curr.message,
};
}, {});
return errors;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment