Created
October 31, 2023 20:57
-
-
Save turnercore/c285641103edd885859edd582cd9c15e to your computer and use it in GitHub Desktop.
Zod & Server Action Form Pattern
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
'use server' | |
import { z } from 'zod' | |
export default async function serverActionOnFormData(formData: FormData) { | |
// Get the form data into a javascript object | |
const form = Object.fromEntries(formData.entries()) | |
// Validate input with zod by passing the form object to the schema | |
const inputSchema = z.object({ | |
id: z.string().uuid(), | |
title: z.string(), | |
content: z.string().optional(), | |
//.... continue | |
}) | |
// Validate data | |
const result = inputSchema.safeParse(form) | |
if (!result.success) { | |
return { error: result.error.message } | |
} | |
// If we get here, the data is valid and can be used exactly as you would expect | |
// to use it in the rest of your server action. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment