Polski

Tutorial · React · TypeScript

Forms in React – react-hook-form, Zod, accessible errors, async validation and file preview

We build a partner-restaurant application form for a dumpling shop – a Zod schema as the single source of rules and types, react-hook-form without unnecessary renders, errors that screen readers understand, a debounced address-availability check, server errors, a dynamic list of fields and a logo preview before upload.

By · · 20 min read

A form is where an app talks to a human most often – and where it most easily loses them. An "Invalid data" message that doesn't say which field, an error shown only as a red border, or a submit button disabled without explanation cost conversions and exclude people who use screen readers. In this tutorial you will build a form that validates data in three layers, says exactly what to fix, and does not re-render on every keystroke.

Prerequisites: Node.js 22.22+ (24 or 26 LTS recommended), React at the hooks level (see the React tutorial), TypeScript and HTML form basics.

26 → 2
form renders – for 25 keystrokes: `useState` vs react-hook-form
3
validation layers – HTML, client (Zod + async), server
0
`useState` per field – react-hook-form holds the values
1
schema – rules, messages and types in one place

Three layers of validation

Client-side validation is a convenience for the user, not a security measure. Anyone who opens DevTools can send whatever they want to the API. So you plan three layers, each with a different job:

Diagram: Who checks what – from HTML attributes to the server

HTML attributes don't validate here (the form has noValidate so browser bubbles don't mix with our messages), but they still work for you: type="email" and inputMode="numeric" bring up the right keyboard on phones, and autocomplete lets the browser fill in fields – which is also an accessibility requirement (WCAG 1.3.5).

Step 1. The project

npm create vite@latest pierogi-partner-form -- --template react-ts
cd pierogi-partner-form
npm install react-hook-form zod @hookform/resolvers
npm run dev

Configuration, app entry and styles

package.json
{
  "name": "pierogi-partner-form",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@hookform/resolvers": "^7.0.9",
    "react": "^19.3.1",
    "react-dom": "^19.3.1",
    "react-hook-form": "^7.92.0",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/react": "^19.3.3",
    "@types/react-dom": "^19.3.0",
    "@vitejs/plugin-react": "^6.3.0",
    "typescript": "~7.0.2",
    "vite": "^8.4.0"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "es2023",
    "lib": ["ES2023", "DOM", "DOM.Iterable"],
    "module": "esnext",
    "moduleResolution": "bundler",
    "types": ["vite/client"],
    "jsx": "react-jsx",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "skipLibCheck": true
  },
  "include": ["src", "vite.config.ts"]
}
vite.config.ts
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({ plugins: [react()] });
index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pierogi – become a partner</title>
  </head>
  <body>
    <main id="root"></main>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { PartnerForm } from "./partner/PartnerForm.tsx";
import "./styles.css";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <PartnerForm />
  </StrictMode>,
);
src/styles.css
:root { font-family: system-ui, sans-serif; color: #1f2328; }
body { margin: 0; }
form { max-width: 560px; margin: 0 auto; padding: 1rem; }
.field { display: flex; flex-direction: column; gap: .25rem; margin-bottom: 1rem; }
.field input:not([type="checkbox"]):not([type="file"]) { padding: .5rem; font-size: 1rem; border: 1px solid #8c959f; border-radius: 6px; }
.field.has-error input { border: 2px solid #c92a2a; }
.field.checkbox { flex-direction: row; flex-wrap: wrap; align-items: center; }
.hint { margin: 0; font-size: .875rem; color: #57606a; }
.error { margin: 0; color: #c92a2a; font-weight: 600; }
.summary { border: 2px solid #c92a2a; border-radius: 8px; padding: .5rem 1rem; margin-bottom: 1rem; }
.summary:focus { outline: 3px solid #4263eb; outline-offset: 2px; }
.summary h2 { font-size: 1.1rem; margin: .25rem 0; }
fieldset { border: 1px solid #d0d7de; border-radius: 8px; margin-bottom: 1rem; }
.zone { display: grid; grid-template-columns: 2fr 1fr auto; gap: .5rem; align-items: end; }
.slug-status { margin: -.75rem 0 1rem; font-size: .875rem; min-height: 1.2em; }
.slug-available { color: #2b8a3e; }
.slug-taken { color: #c92a2a; }
.logo-input img { display: block; margin-top: .5rem; object-fit: contain; border: 1px solid #d0d7de; border-radius: 8px; }
button { padding: .5rem 1rem; font-size: 1rem; cursor: pointer; }
@media (max-width: 520px) { .zone { grid-template-columns: 1fr; } }

Step 2. The Zod schema: rules, messages and types

You start with the schema, not with JSX. It describes what data the form must produce and immediately gives you two types: z.input (what is in the fields) and z.output (what you get after validation and transformations).

Form schema and NIP validation

src/partner/schema.ts
import { z } from "zod";
import { isValidNip, normalizeNip } from "./nip.ts";

const MAX_LOGO_BYTES = 2 * 1024 * 1024;

export const zoneSchema = z.object({
  city: z.string().trim().min(2, "Enter a city or district"),
  minOrder: z.number({ error: "Enter an amount" }).min(0, "Cannot be negative").max(500, "Max 500 zł"),
});

// One source of truth: validation rules, error messages and TypeScript types.
export const partnerSchema = z.object({
  name: z.string().trim().min(2, "Enter the restaurant name").max(80, "Max 80 characters"),
  email: z.email("Enter a valid e-mail address"),
  nip: z
    .string()
    .trim()
    .refine(isValidNip, "Invalid NIP – check the digits (10 digits, valid checksum)")
    .transform(normalizeNip),
  slug: z
    .string()
    .trim()
    .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase letters, digits and hyphens")
    .min(3, "At least 3 characters")
    .max(40, "Max 40 characters"),
  zones: z.array(zoneSchema).min(1, "Add at least one delivery zone").max(10, "Max 10 zones"),
  logo: z
    .file()
    .max(MAX_LOGO_BYTES, "The logo must be smaller than 2 MB")
    .mime(["image/png", "image/jpeg", "image/webp"], "Use PNG, JPG or WebP")
    .nullable(),
  terms: z.boolean().refine((v) => v, "You must accept the partner terms"),
});

export type PartnerFormInput = z.input<typeof partnerSchema>;
export type PartnerFormOutput = z.output<typeof partnerSchema>;
src/partner/nip.ts
// Polish tax ID (NIP): 10 digits, the last one is a checksum (weighted sum mod 11).
const WEIGHTS = [6, 5, 7, 2, 3, 4, 5, 6, 7];

export function normalizeNip(value: string): string {
  return value.replace(/[\s-]/g, "");
}

export function isValidNip(value: string): boolean {
  const nip = normalizeNip(value);
  if (!/^\d{10}$/.test(nip)) return false;
  const digits = [...nip].map(Number);
  const sum = WEIGHTS.reduce((acc, w, i) => acc + w * digits[i]!, 0);
  const check = sum % 11;
  return check !== 10 && check === digits[9];
}

Worth noting:

  • Messages are written for humans: "Invalid NIP – check the digits" instead of "Invalid input". The message says what to fix (WCAG 3.3.3).
  • refine + transform for the NIP: first you check the checksum on what the user typed (with dashes), then normalize to digits only. In onValid you already get a clean 5260….
  • Zod 4: z.email() is a top-level function, z.file() validates a File object (.max() in bytes, .mime()), and the { error: "…" } parameter replaced the old message.
  • zones as an array of objects with min(1) – the "add at least one zone" error belongs to the whole array, not a single field.

Step 3. An accessible field: label, hint and error

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step 4. Debounced async validation
  • Step 5. A logo with preview
  • Step 6. Putting the form together
  • When react-hook-form and when React 19 form actions
  • Common mistakes
  • Check yourself
  • What next

Create a free account · Sign in