Skip to content

Instantly share code, notes, and snippets.

@JTRNS
Created April 8, 2024 17:30
Show Gist options
  • Save JTRNS/f5c54fdc8fdeffb485bafae582bc8d77 to your computer and use it in GitHub Desktop.
Save JTRNS/f5c54fdc8fdeffb485bafae582bc8d77 to your computer and use it in GitHub Desktop.
Zod FormData Helper
import { z } from "zod";
type ParsedFormData<T extends z.AnyZodObject> = {
data: null;
errors: z.typeToFlattenedError<z.infer<T>>['fieldErrors']
} | {
data: z.infer<T>;
errors: null;
}
export async function parseFormData<
Schema extends z.AnyZodObject
>(schema: Schema, request: Request,): Promise<ParsedFormData<Schema>> {
const formdata = await request.formData();
const obj = Object.fromEntries(formdata);
const result = await schema.safeParseAsync(obj);
return result.success
? { data: result.data, errors: null }
: { data: null, errors: result.error.flatten().fieldErrors };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment