Skip to content
Data & CachingChapter 18 / 34Intermediate4 min read

Forms & Validation

Learn Next.js forms with Zod validation, Server Actions and useActionState for errors, pending state and safe data handling.

On this page

1. What are forms and validation?

Validation means checking that what the user sent has the right shape: the email is valid, the password is long enough, the quantity is a number. The browser's required validation is only a convenience. Real validation always happens on the server.

2. Why does it matter?

Without server validationZod + Server Action
Checked only in the browser, can be bypassedSchema on the server, cannot be bypassed
if else for every fieldOne schema, all rules in one place
Showing error messages is hardfieldErrors go straight into the UI
Writing TypeScript types separatelyThe type is inferred from the schema
Risk of double submitThe button is disabled with isPending

3. Where is it used?

FormValidation rules
SignupEmail format, password length, name required
Contact formMinimum message length, valid email
CheckoutAddress fields, positive quantity
Profile editUnique username, maximum bio length
Search filtersPrice range numbers, category enum

4. How does it work?

Form validation flow
The user submits the form
useActionState calls the action
The Server Action reads FormData
Zod safeParse
Fail: errors are returned and shown on the form
Pass: save to the database + redirect

5. Code example

Step 1: schema and action

ts
"use server";

import * as z from "zod";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";

const ContactSchema = z.object({
  name: z.string().trim().min(2, { error: "Name must be at least 2 characters" }),
  email: z.email({ error: "Enter a valid email" }),
  message: z.string().trim().min(10, { error: "Write a slightly longer message" }),
});

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

export async function sendMessage(
  prevState: ContactState,
  formData: FormData,
): Promise<ContactState> {
  const result = ContactSchema.safeParse({
    name: formData.get("name"),
    email: formData.get("email"),
    message: formData.get("message"),
  });

  if (!result.success) {
    return { errors: z.flattenError(result.error).fieldErrors };
  }

  await db.message.create({ data: result.data });
  redirect("/contact/thanks");
}

Step 2: client form with useActionState

tsx
"use client";

import { useActionState } from "react";
import { sendMessage, type ContactState } from "./actions";

const initialState: ContactState = {};

export function ContactForm() {
  const [state, formAction, isPending] = useActionState(sendMessage, initialState);

  return (
    <form action={formAction}>
      <input name="name" placeholder="Name" />
      {state.errors?.name && <p>{state.errors.name[0]}</p>}

      <input name="email" type="email" placeholder="Email" />
      {state.errors?.email && <p>{state.errors.email[0]}</p>}

      <textarea name="message" placeholder="Message" />
      {state.errors?.message && <p>{state.errors.message[0]}</p>}

      <button type="submit" disabled={isPending}>
        {isPending ? "Sending..." : "Send"}
      </button>
    </form>
  );
}

How does the code work?

PartMeaning
z.object({...})The schema of the form, with rules for each field
safeParse(...)Does not throw an error, returns success as true or false
z.flattenError(...).fieldErrorsAn object with the error messages of each field
prevStateWith useActionState, the first argument of the action is the previous state
useActionState(action, initial)Returns [state, formAction, isPending]
isPendingDisables the button while the submit is running
result.dataValidated and typed data, save only this

Interview tip

When you use useActionState, the signature of the Server Action changes: the first argument is prevState and the second is formData. Forgetting this is the most common interview trap.

6. Common mistakes

Mistake: Relying only on client side validation

Why? Anyone can send bad data straight to the Server Action with DevTools or curl.

Better: Always run safeParse with a Zod schema in every Server Action.

Mistake: Forgetting the prevState argument with useActionState

Why? The first argument is the state and FormData comes second, otherwise formData.get crashes.

Better: Always write the signature with both prevState and formData.

Mistake: Using parse and leaving the error unhandled

Why? parse throws an error on failure, and the user sees a generic error page.

Better: Use safeParse and return the errors in the state.

Mistake: Putting raw formData into the database

Why? Extra or wrong fields can also be saved, such as a role of admin.

Better: Save only result.data, which has passed the schema.

7. What to learn before and after

Final quick revision

PointDetail
Validation libraryZod, with safeParse
Field errorsz.flattenError(error).fieldErrors
HookuseActionState(action, initialState)
Action signature(prevState, formData)
LoadingDisable the button with isPending