Last active
May 12, 2024 00:24
-
-
Save DanielBaulig/29905c9429db0c7c565abc8e3f212581 to your computer and use it in GitHub Desktop.
Simple, stupid zod FormData validation
This file contains 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 { z } from 'zod'; | |
// If you feel zod-form-data is too bulky for what | |
// you're trying to do, try this: | |
export const zfd = <T extends z.ZodRawShape>(shape: T) => { | |
return z.custom<FormData>().transform( | |
(fd) => Object.fromEntries( | |
fd.entries() as IterableIterator<[string, string]> | |
) | |
).pipe(z.object(shape)); | |
} | |
const schema = zfd({ | |
username: z.string().min(3), | |
email: z.string().email(), | |
age: z.coerce.number(), | |
}) | |
const formData = // get your FormData from somewhere | |
const { | |
username, | |
email, | |
age, | |
} = schema.parse(formData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment