Menu

Validating Forms with useActionState

Lesson 2: Validating Forms with useActionState

Why validate on the server?

Browser validation (required, type="email") improves the experience, but it can be bypassed. The server must validate every input before it touches the database.

Layer Purpose Can be bypassed?
HTML attributes (required, minLength) Quick feedback Yes
Client-side JavaScript checks Richer feedback Yes
Server validation (Zod, Valibot) Protects data No

Example

// app/enrol/actions.ts
'use server';

import { z } from 'zod';
import { redirect } from 'next/navigation';

const EnrolSchema = z.object({
  name: z.string().trim().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Enter a valid email'),
  courseId: z.string().min(1),
});

export type EnrolState = {
  errors?: Partial<Record<'name' | 'email' | 'courseId', string[]>>;
  message?: string;
};

export async function enrol(prevState: EnrolState, formData: FormData): Promise<EnrolState> {
  const parsed = EnrolSchema.safeParse(Object.fromEntries(formData));

  if (!parsed.success) {
    return { errors: parsed.error.flatten().fieldErrors, message: 'Please fix the errors below.' };
  }

  await saveEnrolment(parsed.data);
  redirect('/dashboard?enrolled=1');
}
// app/enrol/EnrolForm.tsx
'use client';

import { useActionState } from 'react';
import { enrol, type EnrolState } from './actions';

export function EnrolForm({ courseId }: { courseId: string }) {
  const [state, formAction, isPending] = useActionState<EnrolState, FormData>(enrol, {});

  return (
    <form action={formAction}>
      <input type="hidden" name="courseId" value={courseId} />

      <label htmlFor="name">Name</label>
      <input id="name" name="name" />
      {state.errors?.name && <p className="text-red-600">{state.errors.name[0]}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" />
      {state.errors?.email && <p className="text-red-600">{state.errors.email[0]}</p>}

      <button disabled={isPending}>{isPending ? 'Enrolling…' : 'Enrol now'}</button>
      {state.message && <p aria-live="polite">{state.message}</p>}
    </form>
  );
}

How it works

  • useActionState wraps the action. The action now receives the previous state as its first argument.
  • Whatever the action returns becomes the new state, which the form displays.
  • isPending is true while the action runs.
  • safeParse never throws; it returns either clean data or a list of errors.
  • redirect() ends the action and navigates. Call it after the work is done and outside any try/catch.

Common mistakes

Mistake Effect Fix
Trusting formData.get() values Wrong types, injection risks Parse with a schema; convert types explicitly
Throwing for validation errors Error page instead of a message Return errors as state
Forgetting the prevState parameter formData is undefined Signature is (prevState, formData) with useActionState
Clearing all fields after an error Users retype everything Return submitted values in state or use defaultValue

Key takeaways

  • Validate on the server with a schema every time.
  • useActionState connects the action's return value to the UI and gives you a pending flag.

Try it: Build the LearnHub enrolment form with Zod validation, field-level errors, and a disabled button while submitting.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details