How do you validate form data on the server before saving it, and show validation errors back to the user?
Short answer
Inside your server action, you check the submitted values against your validation rules, often using a library like zod, and if validation fails, you return an object describing the errors instead of throwing, which you can then read on the client using the useActionState hook…
Advertisement
AModel answer
Inside your server action, you check the submitted values against your validation rules, often using a library like zod, and if validation fails, you return an object describing the errors instead of throwing, which you can then read on the client using the useActionState hook to display messages next to the relevant fields.
'use server';
import { z } from 'zod';
const schema = z.object({ email: z.string().email() });
export async function submitContact(prevState, formData) {
const result = schema.safeParse({ email: formData.get('email') });
if (!result.success) {
return { error: 'Please enter a valid email address' };
}
await saveContact(result.data);
return { success: true };
}Real-world example
A newsletter signup form shows a clear error message right under the email field if a visitor types an invalid email address, thanks to validation happening safely inside the server action.
Likely follow-ups
- What is the useActionState hook and how does it connect to a server action?
- Should validation also happen on the client for a faster response?
Related topics