Lab: A Multi-Step Signup Form with One Shared Schema
Build a two-step signup form where one schema validates on the client and on the server, errors are summarised and focused, and the submit button shows its pending state.
Contentsand lesson path
On this page
- Goals and preparation
- Step 1: one schema, two callers
- Step 2: the summary, the fields and step one
- Step 3: submit everything to the action
- Step 4: the pending button
- Step 5: run the whole flow
- Check your understanding
- Apply it
- Review prompt
Lessons of Forms & Validation
- Native Form Controls Done Right Concept · 20 min
- Constraint Validation and Error Messages Everyone Can Perceive Worked example · 25 min
- Controlled, Uncontrolled and FormData Concept · 20 min
- Form Actions and Pending States in React Worked example · 25 min
- Lab: A Multi-Step Signup Form with One Shared Schema Lab · 30 min
- Check: Audit a Form Knowledge check · 6 questions
What you will learn
- Build forms from native controls with visible labels, grouped fields, correct input types and autocomplete tokens, fully usable with a keyboard.
- Validate with native constraints and a shared schema, showing inline errors linked to their fields and an error summary that screen readers announce.
- Handle submission in React with controlled or uncontrolled inputs and form actions (useActionState, useFormStatus), including pending state, double-submit prevention and server-returned errors, treating server-side validation as mandatory.
Prerequisites: React Components & State
01. Goals and preparation
This lab brings the three lessons of this skill together in one component. You build a signup form in two steps — account, then profile — where a single schema defines what valid means. Step 1 is parsed by that schema in the browser before the form advances. The final submit goes to a React action that parses the same schema again on the server side, adds a check only a server can make, and returns per-field errors. Failures are reported twice: inline next to each field, and in a summary at the top that receives focus and links to every problem. While the action runs, the button says so and refuses clicks.
Everything runs under Vitest with jsdom, so you get a complete, checkable result without a network or a browser session. Versions this lab was last run with: Node 22.23.2, React 19.3.1, Zod 4.6.7, Vitest 5.1.2, jsdom 31.0.1, Testing Library 16.3.3 with @testing-library/dom 10.4.2 and user-event 14.6.13. Create the project and install (an empty folder, npm init -y, then):
npm install [email protected] [email protected] [email protected]
npm install -D [email protected] [email protected] \
@testing-library/[email protected] @testing-library/[email protected] \
@testing-library/[email protected]lab/
package.json
vitest.config.mts
src/
signup-schema.ts one schema, both sides
signup-form.tsx the two-step form component
schema.test.ts checks the schema and the mock action
signup-form.test.tsx drives the whole flow in jsdomimport { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
globals: true,
include: ['src/**/*.test.tsx', 'src/**/*.test.ts'],
},
});globals: true lets Testing Library clean up the rendered DOM after every test; without it, queries from one test find leftovers from the last. The .mts extension tells Node to load the config as an ES module: npm init -y writes a package.json without "type": "module", and with a plain .ts name Vite 8 prints a warning about ESM syntax in a CommonJS file before every run. Every command below runs from the lab folder.
02. Step 1: one schema, two callers
Write the rules once. Zod schemas describe the data; the two step schemas combine into a full-signup schema for the server. validateStep turns a failed parse into a plain map of field name to message, which is exactly what both the inline messages and the summary need. The mock action parses the full payload with the combined schema, then adds the check a schema cannot express: whether the email is already registered. That is the division of labour — the client parse gives instant feedback, the server parse protects the data, and neither trusts the other.
import { z } from 'zod';
// Step 1: the account fields.
export const accountSchema = z.object({
fullName: z.string().trim().min(2, 'Enter your full name.'),
email: z.email('Enter a valid email address.'),
password: z.string().min(8, 'Use at least 8 characters.'),
});
// Step 2: the public profile.
export const profileSchema = z.object({
displayName: z.string().trim().min(2, 'Pick a display name.'),
website: z.url('Enter a full URL, e.g. https://example.com')
.or(z.literal('')),
});
// The whole signup payload, used by the "server" only.
export const signupSchema = accountSchema.extend({
displayName: profileSchema.shape.displayName,
website: profileSchema.shape.website,
});
export type AccountValues = z.output<typeof accountSchema>;
export type FieldErrors = Record<string, string>;
export function validateStep<T>(
schema: z.ZodType<T>,
data: unknown,
): { ok: true; data: T } | { ok: false; errors: FieldErrors } {
const result = schema.safeParse(data);
if (result.success) return { ok: true, data: result.data };
const errors: FieldErrors = {};
for (const issue of result.error.issues) {
const key = String(issue.path[0] ?? 'form');
if (!errors[key]) errors[key] = issue.message;
}
return { ok: false, errors };
}
export type SignupState =
| {
status: 'error';
fieldErrors: FieldErrors;
values?: { displayName?: string; website?: string };
}
| { status: 'success'; displayName: string };
// The mock server action: same schema, plus checks only the server
// can make.
export async function signupAction(
_prev: SignupState | null,
formData: FormData,
): Promise<SignupState> {
await new Promise((resolve) => setTimeout(resolve, 300)); // network
const raw = Object.fromEntries(formData);
const values = {
displayName: String(raw.displayName ?? ''),
website: String(raw.website ?? ''),
};
const result = validateStep(signupSchema, raw);
if (!result.ok) {
return { status: 'error', fieldErrors: result.errors, values };
}
if (result.data.email === '[email protected]') {
return {
status: 'error',
fieldErrors: { email: 'That email is already registered.' },
values,
};
}
return { status: 'success', displayName: result.data.displayName };
}import { describe, expect, it } from 'vitest';
import { accountSchema, signupAction, validateStep } from './signup-schema';
describe('one shared schema', () => {
it('gives the client a per-field error map', () => {
const bad = validateStep(accountSchema, {
fullName: 'A',
email: 'not-an-email',
password: 'short',
});
console.log('client parse ->', JSON.stringify(bad));
expect(bad.ok).toBe(false);
const good = validateStep(accountSchema, {
fullName: 'Rin Dao',
email: '[email protected]',
password: 'correct-horse-1',
});
console.log('client parse ok ->', JSON.stringify(good));
expect(good.ok).toBe(true);
});
it('the server re-checks the same schema and adds its own checks', async () => {
const fd = new FormData();
fd.set('fullName', 'Rin Dao');
fd.set('email', '[email protected]');
fd.set('password', 'correct-horse-1');
fd.set('displayName', 'Rin');
fd.set('website', '');
const state = await signupAction(null, fd);
console.log('server check ->', JSON.stringify(state));
expect(state.status).toBe('error');
});
it('a valid payload returns success', async () => {
const fd = new FormData();
fd.set('fullName', 'Rin Dao');
fd.set('email', '[email protected]');
fd.set('password', 'correct-horse-1');
fd.set('displayName', 'Rin');
fd.set('website', 'https://rin.example.com');
const state = await signupAction(null, fd);
console.log('server check ->', JSON.stringify(state));
expect(state.status).toBe('success');
});
});npx vitest run src/schema.test.tsclient parse -> {"ok":false,"errors":{"fullName":"Enter your full name.",
"email":"Enter a valid email address.",
"password":"Use at least 8 characters."}}
client parse ok -> {"ok":true,"data":{"fullName":"Rin Dao",
"email":"[email protected]","password":"correct-horse-1"}}
server check -> {"status":"error","fieldErrors":
{"email":"That email is already registered."},
"values":{"displayName":"Rin","website":""}}
server check -> {"status":"success","displayName":"Rin"}
Test Files 1 passed (1)
Tests 3 passed (3)Vitest also prints a stdout | src/schema.test.ts > … header above each test's lines, a tick per test and a timing line; they are left out here. The important shape is the error map: one message per field name, extracted from the first issue on each path, ready to be rendered next to fields and listed in a summary.
03. Step 2: the summary, the fields and step one
Three small components carry most of the accessibility work. ErrorSummary renders the list of problems and moves focus to itself — a focused element is what screen readers announce, so the user hears the list and each link's destination. Field keeps the wiring from the native-controls lesson automatic: a visible label, aria-invalid and an aria-describedby that points at the message only while there is one. SignupForm parses step 1 with the shared schema in its submit handler.
import { useEffect, useRef, useState, useActionState } from 'react';
import type { ComponentProps } from 'react';
import { useFormStatus } from 'react-dom';
import {
accountSchema,
signupAction,
validateStep,
type AccountValues,
type FieldErrors,
type SignupState,
} from './signup-schema';
function ErrorSummary({ errors }: { errors: FieldErrors }) {
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
box.current?.focus(); // announces the heading; screen readers
}, [errors]); // read the links
const items = Object.entries(errors);
if (items.length === 0) return null;
return (
<div
ref={box}
tabIndex={-1}
role="alert"
aria-labelledby="error-summary-title"
data-testid="error-summary"
>
<h2 id="error-summary-title">There is a problem</h2>
<ul>
{items.map(([field, message]) => (
<li key={field}>
<a href={`#${field}`}>{message}</a>
</li>
))}
</ul>
</div>
);
}
function Field({
id,
label,
error,
...input
}: { id: string; label: string; error?: string } & ComponentProps<'input'>) {
return (
<div>
<label htmlFor={id}>{label}</label>
<input
id={id}
name={id}
aria-invalid={error ? true : undefined}
aria-describedby={error ? `${id}-error` : undefined}
{...input}
/>
{error ? <p id={`${id}-error`}>{error}</p> : null}
</div>
);
}export function SignupForm({
action = signupAction,
}: { action?: typeof signupAction }) {
const [step, setStep] = useState<1 | 2>(1);
const [account, setAccount] = useState<AccountValues | null>(null);
const [stepErrors, setStepErrors] = useState<FieldErrors>({});
const submitWithAccount = async (
prev: SignupState | null,
formData: FormData,
) => {
if (account) {
formData.set('fullName', account.fullName);
formData.set('email', account.email);
formData.set('password', account.password);
}
return action(prev, formData);
};
const [state, formAction] = useActionState(submitWithAccount, null);
if (state?.status === 'success') {
return (
<p role="status">
Welcome, {state.displayName}! Check your inbox to verify your
email.
</p>
);
}
if (step === 1) {
return (
<form key="account" noValidate
onSubmit={(event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const result = validateStep(accountSchema,
Object.fromEntries(data));
if (result.ok) {
setAccount(result.data);
setStepErrors({});
setStep(2);
} else {
setStepErrors(result.errors);
}
}}
>
<ErrorSummary errors={stepErrors} />
<Field id="fullName" label="Full name" type="text"
autoComplete="name" required
error={stepErrors.fullName} />
<Field id="email" label="Email" type="email" autoComplete="email"
required error={stepErrors.email} />
<Field id="password" label="Password" type="password"
autoComplete="new-password" required minLength={8}
error={stepErrors.password} />
<button type="submit">Next</button>
</form>
);
}
// ... step 2 follows in the next step
}Two deliberate choices in that markup. The native attributes stay — required, type, minLength, the autocomplete tokens — because they describe the data, drive mobile keyboards and feed password managers. But noValidate hands messaging to the schema, so the user gets one error surface with your words instead of a browser bubble in a language you do not control. And each <form> carries a distinct key, which is not decoration: you will see in the tests what React does without it.
04. Step 3: submit everything to the action
Step 2 submits to the action through submitWithAccount, which injects the step-1 account credentials into the FormData in memory. That avoids hidden password inputs on step 2: the password is in the DOM only while the user types it on step 1, not for the rest of the flow, which leaves less for a session-replay tool or a browser extension that reads the page to pick up later. Server validation errors come back through useActionState into the summary and Field wiring, while defaultValue preserves user-typed inputs so React 19's automatic form reset does not wipe them.
const serverErrors =
state?.status === 'error' ? state.fieldErrors : undefined;
return (
<form key="profile" noValidate action={formAction}>
<ErrorSummary errors={serverErrors ?? {}} />
<Field
id="displayName"
label="Display name"
type="text"
required
defaultValue={state?.status === 'error' ? state.values?.displayName : undefined}
error={serverErrors?.displayName}
/>
<Field
id="website"
label="Website (optional)"
type="url"
defaultValue={state?.status === 'error' ? state.values?.website : undefined}
error={serverErrors?.website}
/>
<SubmitButton />
</form>
);
}The keys earn their keep here. Both steps return a <form> from the same position in the tree, and React reuses the element instead of remounting — so without the keys, the inputs are matched by position too. The full name typed in step 1 is still sitting in the display-name input on step 2, and the email in the website field, because an uncontrolled input keeps its DOM value when React reuses it. The password field has no counterpart (its slot now holds the submit button), so it is the only one removed. Different content in the same slot needs a different key.
05. Step 4: the pending button
The last component reads pending from useFormStatus and disables itself while the action runs. It gives slow submissions a visible signal and stops the accidental double click.
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Creating your account…' : 'Create account'}
</button>
);
}06. Step 5: run the whole flow
The flow test drives all four behaviours. The gated action keeps the first submission in flight until the test releases it, which is what makes the pending state observable.
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { UserEvent } from '@testing-library/user-event';
import { beforeEach, describe, expect, it } from 'vitest';
import { SignupForm } from './signup-form';
import type { SignupState } from './signup-schema';
let calls = 0;
let resolvers: Array<() => void> = [];
let lastBody: Record<string, string> = {};
const gatedAction = async (
_prev: SignupState | null,
formData: FormData,
): Promise<SignupState> => {
calls += 1;
lastBody = Object.fromEntries(formData) as Record<string, string>;
const values = {
displayName: String(lastBody.displayName ?? ''),
website: String(lastBody.website ?? ''),
};
await new Promise<void>((resolve) => resolvers.push(resolve));
if (lastBody.email === '[email protected]') {
return {
status: 'error',
fieldErrors: { email: 'That email is already registered.' },
values,
};
}
return { status: 'success', displayName: lastBody.displayName ?? '' };
};
const releaseAll = () => {
for (const resolve of resolvers) resolve();
resolvers = [];
};
const ACCOUNT = {
fullName: 'Rin Dao',
email: '[email protected]',
password: 'correct-horse-1',
};
async function completeStep1(user: UserEvent) {
await user.type(screen.getByLabelText('Full name'), ACCOUNT.fullName);
await user.type(screen.getByLabelText('Email'), ACCOUNT.email);
await user.type(screen.getByLabelText('Password'), ACCOUNT.password);
await user.click(screen.getByRole('button', { name: 'Next' }));
}describe('multi-step signup', () => {
beforeEach(() => {
calls = 0;
resolvers = [];
lastBody = {};
});
it('an empty step 1 shows a focused summary that links to each field',
async () => {
const user = userEvent.setup();
render(<SignupForm action={gatedAction} />);
await user.click(screen.getByRole('button', { name: 'Next' }));
const summary = screen.getByTestId('error-summary');
expect(document.activeElement).toBe(summary);
const links = Array.from(summary.querySelectorAll('a'));
console.log('focus moved to ->',
document.activeElement === summary ? 'summary' : 'elsewhere');
for (const link of links) {
console.log('summary link ->', link.getAttribute('href'),
JSON.stringify(link.textContent));
}
const email = screen.getByLabelText('Email');
console.log('email aria-invalid ->',
email.getAttribute('aria-invalid'));
const described = document.getElementById(
email.getAttribute('aria-describedby') ?? '',
);
console.log('email describedby target ->', described?.textContent);
expect(links.map((l) => l.getAttribute('href'))).toEqual([
'#fullName',
'#email',
'#password',
]);
});
it('a valid step 1 advances to the profile step', async () => {
const user = userEvent.setup();
render(<SignupForm action={gatedAction} />);
await completeStep1(user);
console.log('after a valid step 1 ->',
screen.getByText('Display name') ? 'step 2 shown' : '?');
expect(screen.getByLabelText('Display name')).toBeTruthy();
});
it('the server re-checks the same schema and reports per field',
async () => {
const user = userEvent.setup();
render(<SignupForm />); // the real mock action, 300 ms network
await completeStep1(user);
await user.type(screen.getByLabelText('Display name'), 'R');
await user.type(screen.getByLabelText('Website (optional)'),
'not-a-url');
await user.click(screen.getByRole('button',
{ name: 'Create account' }));
const summary = await screen.findByTestId('error-summary',
undefined, { timeout: 3000 });
for (const link of summary.querySelectorAll('a')) {
console.log('server error listed ->',
JSON.stringify(link.textContent));
}
expect(document.activeElement).toBe(summary);
const nameInput =
screen.getByLabelText('Display name') as HTMLInputElement;
await waitFor(() =>
expect(nameInput.getAttribute('aria-invalid')).toBe('true'),
);
expect(nameInput.value).toBe('R');
const websiteInput =
screen.getByLabelText('Website (optional)') as HTMLInputElement;
expect(websiteInput.value).toBe('not-a-url');
});
it('the action receives every value and the button blocks clicks',
async () => {
const user = userEvent.setup();
render(<SignupForm action={gatedAction} />);
await completeStep1(user);
await user.type(screen.getByLabelText('Display name'), 'Rin');
await user.click(screen.getByRole('button',
{ name: 'Create account' }));
const button = await screen.findByText('Creating your account…');
console.log('while pending ->', button.textContent,
'| disabled =', (button as HTMLButtonElement).disabled);
expect((button as HTMLButtonElement).disabled).toBe(true);
expect(calls).toBe(1);
console.log('FormData received by the action ->',
JSON.stringify(lastBody, null, 2));
releaseAll();
const welcome = await screen.findByText(/Welcome, Rin!/);
console.log('after success ->', welcome.textContent);
expect(calls).toBe(1);
});
});npx vitest run src/signup-form.test.tsxfocus moved to -> summary
summary link -> #fullName "Enter your full name."
summary link -> #email "Enter a valid email address."
summary link -> #password "Use at least 8 characters."
email aria-invalid -> true
email describedby target -> Enter a valid email address.
after a valid step 1 -> step 2 shown
server error listed -> "Pick a display name."
server error listed -> "Enter a full URL, e.g. https://example.com"
while pending -> Creating your account… | disabled = true
FormData received by the action -> {
"displayName": "Rin",
"website": "",
"fullName": "Rin Dao",
"email": "[email protected]",
"password": "correct-horse-1"
}
after success -> Welcome, Rin! Check your inbox to verify your email.
Test Files 1 passed (1)
Tests 4 passed (4)Then run both files together with npx vitest run. Vitest runs the two files in parallel, so their console lines can interleave in any order; the summary at the end is the stable part:
Test Files 2 passed (2)
Tests 7 passed (7)Read the output against the objectives. The summary takes focus and every link names its field. A schema-valid step 1 advances. Payloads the client never checked — step 2 — come back from the action with per-field messages and aria-invalid on the fields. The action receives every value: the wrapper sets the three step-1 values on the FormData — set() adds a new name at the end, which is why they follow the form's own two fields — with no hidden inputs, so the password is not copied back into the DOM on step 2. The pending button shows the state and refuses clicks. One schema wrote every message you can see.
07. Check your understanding
08. Apply it
Take the lab further:
- Add a confirm-password field with a schema-level check across the two fields (
z.refine), and watch the message appear on the second field only. - Make the action reject a display name that contains a reserved word, and add the error to the summary without changing the component.
- Replace the gated action with one that never resolves and confirm the button stays disabled and labelled — then decide what a timeout should do to that state.
Then rebuild the same flow for the checkout form of the skill practice: address, delivery option, payment method, one schema, the same summary.
09. Review prompt
Without looking back: what does the shared schema parse on each side, and what does the server add that the schema cannot know? How does the summary announce itself, and what makes each error reachable from it? Why do the two forms need distinct keys? What does the pending button stop, and what does it not?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.