Skip to content

Instantly share code, notes, and snippets.

@DanielBaulig
Last active May 12, 2024 00:24
Show Gist options
  • Save DanielBaulig/29905c9429db0c7c565abc8e3f212581 to your computer and use it in GitHub Desktop.
Save DanielBaulig/29905c9429db0c7c565abc8e3f212581 to your computer and use it in GitHub Desktop.
Simple, stupid zod FormData validation
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