Skip to content

Decode FormData into arbitrary Zod schemas #967

Discussion options

You must be logged in to vote

I hope this helps, let me know if you have any questions.

export const decodeForm = async <Schema extends z.ZodTypeAny> (
    formDataOrRequest: FormData | Request,
    schema: Schema,
) => {
    const formData = formDataOrRequest instanceof FormData
        ? formDataOrRequest
        : await formDataOrRequest.clone().formData()

    return schema.parse( Object.fromEntries( formData ) ) as z.infer<Schema>
}
const schema1 = z.object( {
    street: z.string(),
    zipCode: z.preprocess(
        ( zipCode ) => parseInt( z.string().parse( zipCode ), 10 ),
        z.number().positive(),
    ),
    city: z.string(),
} )
type Schema1 = z.infer<typeof schema1>

const { street, zipCode, city } = a…

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by hollandThomas
Comment options

You must be logged in to vote
3 replies
@JacobWeisenburger
Comment options

@JacobWeisenburger
Comment options

@hollandThomas
Comment options

Comment options

You must be logged in to vote
1 reply
@jjhiggz
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants