Created
January 8, 2025 09:40
-
-
Save washingtonsoares/850ea7df48343ad7f6cc01229b83c708 to your computer and use it in GitHub Desktop.
withZodSchema.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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