Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 72 ยท Mutations and Forms

Validating Input

Never trust the client: validate Server Action input on the server, return field errors, and share one Zod schema between browser and server code.

The required attribute and the maxlength attribute feel like validation, but they are only hints for honest visitors. Anyone can open the browser's developer tools, delete the attribute, or skip the browser entirely and send a request with a command-line tool. A Server Action is a public endpoint, so whatever arrives there must be treated as untrusted until the server has checked it.

That gives one rule for this whole lesson: always validate on the server; optionally validate on the client too, for speed. The best way to do both without writing the rules twice is a schema: one description of valid data that runs in both places. The popular library for this is Zod. We show it read-only, and then build a tiny validator by hand so you can see exactly what a schema library does.

Real or stand-in? The Zod code below is real and read-only: Zod is an npm package and the code runner has no npm packages. The two live examples use a small hand-written validator with the same shape (a schema, safeParse, field errors). It is a teaching stand-in, much simpler than Zod, and it does not replace it.

Why client checks are not enough

Two kinds of checks

Client checks Fast feedback for honest users.
Server checks The only ones you can rely on.

Do both, but only the server decides.

1 / 2

Validation answers three separate questions: is the data the right shape (are the fields there, are they the right type), is it valid (an email looks like an email, a quantity is between 1 and 99), and is it allowed (does this user have permission, does this record belong to them). Schemas handle the first two. Permission checks are the topic of Authorization and Data Security.

A schema with Zod

Zod lets you describe valid data once, in TypeScript, and get both a runtime check and a static type:

TypeScript
// lib/schemas.ts
import { z } from 'zod';

export const signupSchema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters.').max(50),
  email: z.email('Enter a valid email address.'),
  age: z.coerce.number().int().min(13, 'You must be at least 13.'),
});

export type SignupInput = z.infer<typeof signupSchema>;

z.coerce.number() converts the string a form sends into a number first, which matters because every FormData value is a string. z.infer derives the TypeScript type from the schema, so the type and the rules cannot drift apart.

Use it in the action with safeParse, which never throws. It returns either { success: true, data } or { success: false, error }:

TypeScript
// app/signup/actions.ts
'use server';

import { z } from 'zod';
import { signupSchema } from '@/lib/schemas';

export type SignupState = {
  errors: Record<string, string[] | undefined>;
  message: string;
};

export async function signup(previous: SignupState, formData: FormData): Promise<SignupState> {
  const parsed = signupSchema.safeParse({
    name: formData.get('name'),
    email: formData.get('email'),
    age: formData.get('age'),
  });

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

  // parsed.data is typed as SignupInput and safe to use
  await createUser(parsed.data);
  return { errors: {}, message: 'Welcome aboard!' };
}

Because the action passes only the three named fields into the schema, any extra field an attacker adds (such as role=admin) is never read. This is a good habit worth stating: pick the fields you want from formData; do not spread the whole form into your database call. The form component then shows state.errors.email?.[0] beside the input, exactly as in Building Forms with Server Actions.

What a schema library does

A schema is just data plus a function that walks it. Each field has a list of rules, and each rule can fail with a message. safeParse runs the rules and collects the failures per field.

This first example builds that from scratch: small helpers that make field validators, an object function that applies them, and a safeParse that returns Zod-shaped results. Run it and read the output line by line.

Node.js A tiny schema validator, built by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the three results. The first succeeds and the data comes back cleaned: the name was trimmed and the age is now the number 36, not the string '36'. The second fails on every field and collects all messages, so the user can fix everything in one go. The third is missing name and age, so those fail, and the extra role field simply does not appear in the output: the schema only keeps what it knows.

One schema, two places

The real benefit of a schema is sharing it. The same signupSchema can run in a Client Component to give instant feedback as the user types, and again in the Server Action as the real gate. Import it in both places; do not copy the rules.

TSX
'use client';

import { signupSchema } from '@/lib/schemas';

export function SignupForm() {
  function onBlur(event: React.FocusEvent<HTMLFormElement>) {
    const data = Object.fromEntries(new FormData(event.currentTarget));
    const result = signupSchema.safeParse(data);
    // show result.error messages next to the fields
  }
  // ...
}

The schema file must not import server-only code such as your database, because it is bundled for the browser too. Keep it pure.

Now the part that matters most. The second stand-in shows a form whose client-side check works perfectly, and a hostile request that skips the client entirely. Only the server-side validation stops it.

Node.js The client check can be skipped; the server check cannot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The attacker's request never touches the browser form, so the client rule never runs. In the unprotected run the bad order (quantity -5) is stored. In the protected run the server rejects it with field errors. Notice also that isAdmin never reaches the stored order: the code copies only allowedFields.

Handling the results

A few practical rules make validated actions pleasant to use:

  • Return all errors at once, not just the first, so users fix everything in one pass.
  • Keep messages in plain language that name the field and how to fix it.
  • Return errors as data (see Building Forms with Server Actions) and return the submitted values so the form can refill itself.
  • Do not echo secrets: never send a password back in values.
  • Validate again where it counts. A value that passed validation five minutes ago may no longer be valid when you write it, for example a username that someone else just took. A database UNIQUE constraint is the final guard, and an error from it should turn into a friendly field message.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a Server Action validate its input even when the form already checks it in the browser?

    Anyone can send a POST directly to the endpoint. Client checks only help honest users; the server must enforce the rules.
  2. 2. Why is z.coerce.number() used for a quantity field in a form?

    Everything in FormData is a string or a File. Coercion turns '36' into 36 before checking things like a minimum.
  3. 3. What does safeParse return when the input is invalid?

    safeParse never throws. It returns { success: true, data } or { success: false, error }, so you can turn failures into messages.
  4. 4. What is the safest way to build the data for a database call from a form?

    Picking named fields and using the schema's output prevents extra attacker-supplied fields like isAdmin from reaching your data layer.
  5. 5. Why share one schema between client and server code?

    One schema gives instant client feedback and the real server check from the same rules. The server check still always runs.

Summary

  • Browser attributes and client checks are conveniences; only server-side validation protects your data.
  • Validate shape, validity and permission separately; schemas cover the first two.
  • A Zod schema describes valid data once, gives a runtime check with safeParse and a TypeScript type with z.infer.
  • Remember that FormData values are strings, so coerce numbers and dates, and read only the fields you expect.
  • Return every field error as data, along with the submitted values, and let a database constraint be the final guard.
  • A shared, pure schema file can run in both browser and server; the server run is the one that counts.

Next: Optimistic UI and Refreshing After Mutations