Build a React Booking Form with Accessible Validation
Introduction
This is lesson 3 of chapter 8 (domain capstone). The catalog and detail views exist. Build a React booking form with accessible validation and connect it to the demo reservation state. A visitor chooses seats, fills in a form, receives clear validation feedback, submits, and sees a confirmation, while the seat count for the workshop goes down.
This is where the skills of earlier chapters meet: controlled form inputs and state (chapter 5), reducers, context, and custom hooks (chapter 6), accessible form patterns (chapters 4 and 7), and pure functions that are easy to test. This independent practice project uses a simulated service and a tab-scoped booking list. Review accessible form semantics and validation before connecting the fields, error messages, and submit handler.
Learning objectives
By the end of this lesson you can:
- Build an accessible, controlled booking form with labels, hints, and
autocomplete. - Write a pure validation function and show errors tied to fields.
- Manage demo booking data with a reducer and share it through context.
- Prevent invalid or duplicate submissions and handle the "not enough seats" rule.
- Navigate to a confirmation page using a booking id.
- Add loading and error states for an asynchronous submit.
- Persist minimal demo state in
sessionStoragedefensively. - Move focus and announce errors for keyboard and screen reader users.
1. Design the flow before the code
The workflow has five states.
- Editing: the visitor fills in the form.
- Invalid: a submit attempt found problems; messages are shown.
- Submitting: the request is in progress; the button is disabled.
- Success: navigate to a confirmation for the booking.
- Failure: keep the typed values and show an actionable message. A group-limit failure needs a smaller request or a different contact path.
Each state needs a visible outcome. For example, a rejected request leaves availability unchanged and lets the visitor correct the seat count.
2. Pure validation
Put the rules in one plain function with no React in it:
// src/lib/validateBooking.js
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function validateBooking(values, seatsLeft) {
const errors = {};
if (!values.name.trim()) {
errors.name = 'Enter your name.';
}
if (!values.email.trim()) {
errors.email = 'Enter your email address.';
} else if (!EMAIL.test(values.email.trim())) {
errors.email = 'Enter an email address like name@example.com.';
}
const seats = Number(values.seats);
if (!Number.isInteger(seats) || seats < 1) {
errors.seats = 'Choose at least 1 seat.';
} else if (seats > seatsLeft) {
errors.seats = `Only ${seatsLeft} seats are left.`;
}
return errors; // empty object means valid
}Why a separate function?
- It is testable without rendering anything: pass values, assert the object.
- It is reusable on the client and, later, on a server. Client validation improves usability; server validation is the real security boundary, because the client can be bypassed. State this in your README.
- Messages describe how to fix the problem ("Enter an email address like name@example.com") rather than only that it is wrong.
The email pattern implements this demo's simple input policy and can reject some addresses accepted by other systems. Syntax checks catch common typing mistakes. A real service can verify control of an address through an email confirmation flow.
3. The form component
// src/components/BookingForm.jsx
import { useEffect, useRef, useState } from 'react';
import { validateBooking } from '../lib/validateBooking';
const EMPTY = { name: '', email: '', seats: '1' };
export default function BookingForm({ seatsLeft, onSubmit, submitting, submitError }) {
const [values, setValues] = useState(EMPTY);
const [errors, setErrors] = useState({});
const nameRef = useRef(null);
const emailRef = useRef(null);
const seatsRef = useRef(null);
useEffect(() => {
const firstInvalid = Object.keys(errors)[0];
const fields = { name: nameRef, email: emailRef, seats: seatsRef };
if (firstInvalid) fields[firstInvalid].current?.focus();
}, [errors]);
function handleChange(event) {
const { name, value } = event.target;
setValues((v) => ({ ...v, [name]: value }));
}
function handleSubmit(event) {
event.preventDefault();
if (submitting) return;
const found = validateBooking(values, seatsLeft);
setErrors(found);
if (Object.keys(found).length) return;
onSubmit({
name: values.name.trim(),
email: values.email.trim(),
seats: Number(values.seats),
});
}
return (
<form onSubmit={handleSubmit} noValidate>
<p role="alert" className="form-summary">
{Object.keys(errors).length > 0 ? 'Check the highlighted fields below.' : ''}
</p>
<div className="field">
<label htmlFor="name">Full name</label>
<input
id="name" name="name" ref={nameRef} value={values.name} required readOnly={submitting}
onChange={handleChange} autoComplete="name"
aria-invalid={Boolean(errors.name)}
aria-describedby={errors.name ? 'name-error' : undefined}
/>
{errors.name && <p id="name-error" className="error">{errors.name}</p>}
</div>
<div className="field">
<label htmlFor="email">Email</label>
<input
id="email" name="email" type="email" ref={emailRef} value={values.email} required readOnly={submitting}
onChange={handleChange} autoComplete="email"
aria-invalid={Boolean(errors.email)}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && <p id="email-error" className="error">{errors.email}</p>}
</div>
<div className="field">
<label htmlFor="seats">Seats</label>
<input
id="seats" name="seats" type="number" inputMode="numeric"
min="1" max={seatsLeft} ref={seatsRef} value={values.seats} required readOnly={submitting}
onChange={handleChange}
aria-invalid={Boolean(errors.seats)}
aria-describedby={`seats-hint${errors.seats ? ' seats-error' : ''}`}
/>
<p id="seats-hint" className="hint">{seatsLeft} seats left.</p>
{errors.seats && <p id="seats-error" className="error">{errors.seats}</p>}
</div>
<p role="alert" className="error">{submitError}</p>
<button type="submit" disabled={submitting}>
{submitting ? 'Booking...' : 'Confirm booking'}
</button>
</form>
);
}Add the field styles to src/styles/global.css. Keep text and focus cues visible when a field has an error.
.field { margin-block: var(--space-2); }
.field label { display: block; font-weight: 600; }
.field input { font: inherit; max-inline-size: 100%; box-sizing: border-box; }
.field [aria-invalid="true"] { border: 2px solid var(--color-danger); }
.error { color: var(--color-danger); }
.error:empty, .form-summary:empty { margin: 0; }Form design decisions
| Decision | Reason |
|---|---|
htmlFor/id label pairing |
Click target and accessible name for every input |
noValidate |
Disables the browser's default bubbles so your consistent, accessible messages are used |
aria-invalid and aria-describedby |
Expose invalid state and associate the error with the input |
| Focus in an effect after the error renders | The target has its error text and description before it receives focus |
Persistent role="alert" regions |
Expose submission messages as live updates. Check announcements on the target browser and assistive technology. |
autoComplete on name and email |
Identifies input purpose for these common personal fields and helps browsers offer autofill |
disabled and readOnly during submission |
Shows the pending state and keeps the submitted values stable. The request guard belongs in the handler. |
| Controlled inputs | The UI always reflects the state, and tests can type into them |
This example validates on submit so that a partially typed address does not immediately show an error. The messages reflect the last submission attempt. If you add revalidation on blur, keep focus changes tied to submission attempts.
4. Booking state with a reducer and context
The booking page, confirmation, and workshop views share the demo booking list. Use a reducer for transitions and a provider around the route tree. The lesson on React reducers, refs, and custom hooks explains these building blocks.
// src/state/BookingsProvider.jsx
import { useEffect, useMemo, useReducer } from 'react';
import { getWorkshop } from '../api/workshops';
import { seatsLeftFor } from '../lib/seats';
import { BookingsContext } from './BookingsContext';
const STORAGE_KEY = 'harbor.demo-bookings.v1';
function reducer(state, action) {
if (action.type === 'booked') {
return { bookings: [...state.bookings, action.booking] };
}
return state;
}
function load() {
const bookings = [];
try {
const saved = JSON.parse(sessionStorage.getItem(STORAGE_KEY) ?? '[]');
if (!Array.isArray(saved)) return { bookings };
const seen = new Set();
for (const item of saved) {
if (!item || typeof item.id !== 'string' || !item.id || seen.has(item.id)) continue;
const workshop = getWorkshop(item.workshopId);
if (!workshop || !Number.isSafeInteger(item.seats) || item.seats < 1) continue;
if (item.seats > seatsLeftFor(workshop, bookings)) continue;
if (typeof item.createdAt !== 'string' || Number.isNaN(Date.parse(item.createdAt))) continue;
const { id, workshopId, seats, createdAt } = item;
bookings.push({ id, workshopId, seats, createdAt });
seen.add(id);
}
} catch {
// Unavailable storage or invalid JSON leaves an empty demo list.
}
return { bookings };
}
export function BookingsProvider({ children }) {
const [state, dispatch] = useReducer(reducer, undefined, load);
useEffect(() => {
try {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state.bookings));
} catch {
// Keep the current tab working in memory if storage is unavailable.
}
}, [state.bookings]);
const value = useMemo(() => ({ bookings: state.bookings, dispatch }), [state.bookings]);
return <BookingsContext.Provider value={value}>{children}</BookingsContext.Provider>;
}// src/state/BookingsContext.js
import { createContext, useContext } from 'react';
export const BookingsContext = createContext(null);
export function useBookings() {
const ctx = useContext(BookingsContext);
if (!ctx) throw new Error('useBookings must be used inside BookingsProvider');
return ctx;
}The initializer reads the tab's saved demo state during initialization. React Strict Mode can call it twice in development, so keep writes in the effect and keep the reducer pure. Handle invalid JSON and valid JSON with the wrong shape. Extract only the fields the demo needs. Tab-scoped storage survives reloads in that page session, and each tab manages its own list. It is editable by the browser user and carries no authority over real inventory. React useReducer (opens in a new tab) · MDN sessionStorage (opens in a new tab)
Seats taken come from the fixture plus the tab's bookings. Derive the remaining count from both.
// src/lib/seats.js
export function seatsLeftFor(workshop, bookings) {
const booked = bookings
.filter((b) => b.workshopId === workshop.id)
.reduce((sum, b) => sum + b.seats, 0);
return Math.max(0, workshop.capacity - workshop.seatsTaken - booked);
}// src/hooks/useSeatsLeft.js
import { seatsLeftFor } from '../lib/seats';
import { useBookings } from '../state/BookingsContext';
export function useSeatsLeft(workshop) {
const { bookings } = useBookings();
return workshop ? seatsLeftFor(workshop, bookings) : 0;
}Once App includes the provider below, replace the old seatsLeft import in WorkshopCard.jsx and WorkshopDetail.jsx with import { useSeatsLeft } from '../hooks/useSeatsLeft';. Keep getWorkshop in the detail module. Replace the old calculation with const left = useSeatsLeft(workshop); in both files. Put the detail hook call before its early not-found return so every render calls the hooks in the same order. Replace the availability placeholder with the link below and delete the unused seatsLeft function from api/workshops.js.
<Link className="button" to={'/workshops/' + workshop.id + '/book'}>
Book seats
</Link>5. Connect the booking route and simulated service
The service responds after 600 ms to make pending and failure states visible. For practice, requests for more than ten seats return a group-limit error. Submit eleven seats in the bike-repair workshop to see the error, then try two. Use the local Vite server or HTTPS so crypto.randomUUID() is available. The response contains a demo id, workshop id, seat count, and timestamp. The form's synthetic contact values stay in the form.
// src/api/bookings.js
export async function submitBooking({ workshopId, seats }) {
await new Promise((resolve) => setTimeout(resolve, 600));
if (seats > 10) {
throw new Error('Choose up to 10 seats for an online demo booking.');
}
return {
id: crypto.randomUUID(),
workshopId,
seats,
createdAt: new Date().toISOString(),
};
}// src/pages/BookingPage.jsx
import { useEffect, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { getWorkshop } from '../api/workshops';
import { submitBooking } from '../api/bookings';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useBookings } from '../state/BookingsContext';
import { seatsLeftFor } from '../lib/seats';
import BookingForm from '../components/BookingForm.jsx';
import NotFound from './NotFound.jsx';
export default function BookingPage() {
const { id } = useParams();
const workshop = getWorkshop(id);
if (!workshop) return <NotFound message="We could not find that workshop." />;
return <BookingScreen key={workshop.id} workshop={workshop} />;
}
function BookingScreen({ workshop }) {
useDocumentTitle('Book ' + workshop.title);
const { bookings, dispatch } = useBookings();
const navigate = useNavigate();
const pending = useRef(null);
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState('');
const left = seatsLeftFor(workshop, bookings);
useEffect(() => {
return () => { pending.current = null; };
}, []);
async function handleSubmit({ seats }) {
if (pending.current) return;
const attempt = {};
pending.current = attempt;
setSubmitting(true);
setSubmitError('');
try {
const booking = await submitBooking({ workshopId: workshop.id, seats });
if (pending.current !== attempt) return;
dispatch({ type: 'booked', booking });
navigate('/confirmation', { state: { bookingId: booking.id }, replace: true });
} catch (error) {
if (pending.current !== attempt) return;
pending.current = null;
setSubmitError(error instanceof Error ? error.message : 'Try again in a moment.');
setSubmitting(false);
}
}
if (left === 0 && !submitting) {
return (
<>
<h1>{workshop.title}</h1>
<p>This workshop is fully booked.</p>
<Link to="/workshops">Choose another workshop</Link>
</>
);
}
return (
<>
<h1>Book {workshop.title}</h1>
<p>Practice booking. Enter a fictional name and email address.</p>
<BookingForm
seatsLeft={left}
onSubmit={handleSubmit}
submitting={submitting}
submitError={submitError}
/>
</>
);
}Set the ref before awaiting the service. The guard applies immediately, including before the disabled state renders. The key gives each workshop its own form instance. On unmount, cleanup invalidates that instance's pending result, so a late demo response cannot dispatch or navigate from the old screen. A real server request can commit before a visitor navigates away. Production booking requires an authoritative result and a retry policy.
The confirmation page
// src/pages/Confirmation.jsx
import { Link, useLocation } from 'react-router';
import { getWorkshop } from '../api/workshops';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useBookings } from '../state/BookingsContext';
import { formatDate, formatPrice } from '../lib/format';
export default function Confirmation() {
const { state } = useLocation();
const { bookings } = useBookings();
const booking = bookings.find((item) => item.id === state?.bookingId);
const workshop = booking ? getWorkshop(booking.workshopId) : null;
useDocumentTitle(workshop ? 'Demo booking confirmed' : 'No recent booking');
if (!booking || !workshop) {
return (
<>
<h1>No recent booking</h1>
<p>Start from the workshop list to make a practice booking.</p>
<Link to="/workshops">Browse workshops</Link>
</>
);
}
const total = workshop.priceCents * booking.seats;
return (
<>
<h1>Demo booking confirmed</h1>
<p>Your practice booking has been recorded for this tab session.</p>
<dl className="facts">
<dt>Workshop</dt><dd>{workshop.title}</dd>
<dt>When</dt><dd>{formatDate(workshop.startsAt)}</dd>
<dt>Seats</dt><dd>{booking.seats}</dd>
<dt>Total</dt><dd>{formatPrice(total)}</dd>
</dl>
<Link to="/workshops">Back to workshops</Link>
</>
);
}The layout moves focus to the main content after navigation. The confirmation handles direct visits and missing records. The history entry holds the booking id and the provider holds the booking. replace: true replaces the current form entry. The ref guard addresses repeated submits during the demo request, and a production API needs idempotency for retries. React Router useNavigate (opens in a new tab)
Wire the completed routes
Wrap the route tree once so every page uses the same provider. The BrowserRouter remains in main.jsx.
// src/App.jsx
import { Routes, Route } from 'react-router';
import Layout from './components/Layout.jsx';
import Home from './pages/Home.jsx';
import Catalog from './pages/Catalog.jsx';
import WorkshopDetail from './pages/WorkshopDetail.jsx';
import BookingPage from './pages/BookingPage.jsx';
import Confirmation from './pages/Confirmation.jsx';
import NotFound from './pages/NotFound.jsx';
import { BookingsProvider } from './state/BookingsProvider.jsx';
export default function App() {
return (
<BookingsProvider>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="workshops" element={<Catalog />} />
<Route path="workshops/:id" element={<WorkshopDetail />} />
<Route path="workshops/:id/book" element={<BookingPage />} />
<Route path="confirmation" element={<Confirmation />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BookingsProvider>
);
}Comparison: where to keep what
| Data | Pattern | Why not another? |
|---|---|---|
| Typed form values | Local useState in the form |
Global state would re-render the app on each keystroke |
| Validation messages | Derived from a pure function, kept in form state after submit | Storing them in context spreads form concerns everywhere |
| Demo bookings | Reducer, context, and sessionStorage |
Several routes share bookings within the current tab session |
| Seats left | Computed by seatsLeftFor |
Storing it duplicates data and can disagree |
| Submit status | Local state in the page | Only the page needs submitting |
| Booking id for confirmation | Router state |
Carries the id with the history entry and keeps contact fields out of the route |
Worked example: two visitors compete for the last seats
Problem. Two users see three free seats. One requests two, and the other requests three. Define what the demo and a production booking service can each guarantee.
Step 1: identify the decision point. The demo validates against the seat count of the current tab. Its fixture and session storage are separate from the other user's inventory.
Step 2: put the capacity rule on the server. In production, check the latest availability and record the reservation in one atomic operation. If the two-seat booking commits first, the second request should receive a conflict that includes the remaining capacity. A separate read followed by a later write leaves a race.
Step 3: handle the response. Keep the entered values, update the displayed availability, and explain that the visitor can reduce the requested seats. Use a retry identifier on real writes so a response lost after commit does not create a second booking.
Step 4: check the demo boundary. Book two of the three pottery seats, reopen that workshop in the same tab, and try to reserve two again. The form reports that only one seat remains. A reload can restore the same tab's demo count if session storage is available. A storage event can notify another document of a change in shared storage, but notification alone cannot make competing writes atomic. MDN storage event (opens in a new tab)
Common pitfalls and study tips
- Missing
preventDefault. The page reloads and all state is lost. - Placeholder as label. The placeholder disappears when typing and is not a reliable accessible name; use a
<label>. - Number inputs return strings.
values.seatsis"2"; convert withNumberand validate integers. - Late async results. Invalidate a pending demo attempt when its form screen unmounts so it cannot change another route.
- Mutating state in a reducer.
state.bookings.push(...)breaks React's change detection; return new arrays. - Context value identity. Memoizing the provider value can avoid notifying consumers when the booking list is unchanged. A booking change still needs to reach the readers.
- Assuming parsed JSON is valid data. Check shape and values and handle blocked storage.
- Trusting client validation. It is a convenience, not security.
- Duplicate submissions. Show the pending state and set a ref guard before starting the request.
Study tip. Trace a submit from the event through validation, the pending guard, the service response, and the reducer. Check the error path and the destination route separately.
Mini case study: the gym class signup
A gym signup form has name, phone, and class choice. Users report: pressing Enter on the phone field submits an empty form and shows nothing; screen reader users cannot tell which field failed; after a network error the form is cleared; and sometimes the member gets two confirmation emails.
Task. Identify the cause of each problem and propose the fix.
Solution.
- Enter submits an empty form with no message. Validation runs only in a click handler on the button. Move it into the form's
onSubmitso Enter and click share the path, and show messages for empty fields. - Screen readers cannot tell which field failed. Errors are colored text with no association. Add
aria-invalidandaria-describedbylinking each input to its message, and move focus to the first invalid field after its error appears in the DOM. - Network error clears the form. The submit handler resets state before the request completes. Reset only after success; keep values on failure and show a retry message in a
role="alert"region. - Two emails. The button stays enabled during the request, and impatient users click twice. Track
submittingfor the UI and set an immediate guard before the request. Use an idempotency key with server-side enforcement so a retry of the same operation does not create a second record or send a second email.
Key terms
- Controlled input: an input whose value comes from React state.
- Pure function: same input gives the same output with no side effects.
- Reducer: a function
(state, action) => newStatedescribing transitions. - Context: a way to share values without passing props through every level.
- Lazy initializer: a function used to calculate initial state during initialization. Strict Mode can invoke it twice in development.
aria-describedby: links an element to descriptive text such as an error.- Idempotency: repeating an operation does not change the result beyond the first time.
- Derived state: a value computed from other state rather than stored.
Summary checklist
- Every input has a visible label and an appropriate
autoCompletevalue. - Validation is a pure function with actionable messages.
- Errors are linked to fields, summarized in an alert, and focus moves to the first invalid field.
- Demo bookings use a reducer, context, and defensive
sessionStorage. - Seats left is computed in one function and used everywhere.
- Submit shows progress, guards a pending request, and preserves input on failure.
- Navigation to confirmation uses
replace, and direct visits are handled. - Focus moves to the main content on the confirmation route.
Sources and further reading
- React, reacting to input with state: https://react.dev/learn/reacting-to-input-with-state (opens in a new tab)
- React, extracting state logic into a reducer: https://react.dev/learn/extracting-state-logic-into-a-reducer (opens in a new tab)
- React, passing data deeply with context: https://react.dev/learn/passing-data-deeply-with-context (opens in a new tab)
- MDN, client-side form validation: https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Forms/Form_validation (opens in a new tab)
- W3C WAI, accessible form notifications (opens in a new tab)
- React effect cleanup (opens in a new tab)
- MDN secure-context UUID generation (opens in a new tab)
- WCAG 2.2: https://www.w3.org/TR/WCAG22/ (opens in a new tab)
