Blitz provides some handy utility functions
validateZodSchema
This utility function will validate input using a
zod
schema, and format any errors
to be usable with your form library.
This is currently compatible with both React Final Form and Formik and any others with the same API.
import {validateZodSchema} from 'blitz'
<FinalForm
initialValues={initialValues}
validate={validateZodSchema(schema)}
...
const validationFunction = validateZodSchema(MyZodSchema)
ZodSchema:
a zod schemaparserType:
pass in either the string "sync" or "async" to this
parameter to indicate the type of parsing that must be performed. If
omitted, it defaults to asyncA validation function to pass to a Form component's validate
prop. It
accepts some values and returns an Promise or object containing any
errors.
(values: any, parserType?: "sync" | "async") => Promise<Object> | Object
Note: Passing in a variable that could be either "sync" or "async" is currently not supported. You need to explicitly pass in either "sync" or "async" if you are using the optional parserType parameter.
Please open an issue on Github if you have a compelling use case for this feature
formatZodError
This utility function will take a ZodError and format it nicely to be usable with your form library.
This is currently compatible with both React Final Form and Formik and any others with the same API.
import {formatZodError} from 'blitz'
<FinalForm
initialValues={initialValues}
validate={values => {
try {
schema.parse(values)
} catch (error) {
return formatZodError(error)
}
}}
...
const formattedErrorsObject = formatZodError(myZodError)
ZodError:
a zod errorAn object with errors that makes the same shape as the original schema