Skip to content

Instantly share code, notes, and snippets.

@turnercore
Created October 31, 2023 20:57
Show Gist options
  • Save turnercore/c285641103edd885859edd582cd9c15e to your computer and use it in GitHub Desktop.
Save turnercore/c285641103edd885859edd582cd9c15e to your computer and use it in GitHub Desktop.
Zod & Server Action Form Pattern
'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