Sub topic 11
Validating input and returning errors
This chapter covers how a route action validates form input and sends errors back to the user. It assumes you know React hooks, TypeScript basics, HTTP status codes, and the FormData API. It also assumes you have read the chapter on actions and Form.
Why validate in the action
Browser checks such as required or type="email" help users, but anyone can skip them by sending a request directly. The action runs on the server, so it is the place where input is trusted or rejected.
An action has three ways to finish:
- Return data, which re-renders the route and exposes the value as
actionData. - Return a redirect, which sends the browser to another URL.
- Throw, which hands control to the nearest error boundary.
Validation errors belong in the first group. The user made a mistake that they can fix, so the page should stay put and show the problem next to the form.
Returning errors with a 400 status
The data helper from react-router lets you return a value and set the HTTP status together. Use 400 for invalid input. Returning an error under a 200 status works, but it misrepresents the result to caches, logs, and monitoring.
import { Form, data, redirect } from "react-router";
import type { Route } from "./+types/new";
import { createContact } from "~/contacts.server";
type FieldErrors = { name?: string; email?: string };
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
const email = String(formData.get("email") ?? "").trim();
const errors: FieldErrors = {};
if (!name) errors.name = "Name is required";
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
errors.email = "Enter a valid email address";
}
if (Object.keys(errors).length > 0) {
return data({ errors, values: { name, email } }, { status: 400 });
}
const contact = await createContact({ name, email });
return redirect(`/contacts/${contact.id}`);
}
export default function NewContact({ actionData }: Route.ComponentProps) {
const errors = actionData?.errors;
const values = actionData?.values;
return (
<Form method="post">
<label>
Name
<input
name="name"
defaultValue={values?.name}
aria-invalid={errors?.name ? true : undefined}
/>
</label>
{errors?.name ? <p role="alert">{errors.name}</p> : null}
<label>
Email
<input
name="email"
defaultValue={values?.email}
aria-invalid={errors?.email ? true : undefined}
/>
</label>
{errors?.email ? <p role="alert">{errors.email}</p> : null}
<button type="submit">Save</button>
</Form>
);
}Four details in this example matter.
String(formData.get(...) ?? "")converts the value to a string.FormData.getreturnsstring | File | null, so the cast avoids surprises when a field is missing or a file is sent..trim()runs before the check. Without it, a name made of spaces passes the!nametest.- The action collects all errors before returning. The user sees every problem at once instead of fixing them one per submission.
- The action echoes the submitted values. When the page re-renders,
defaultValuerestores what the user typed.
How the error reaches the component
When the action returns, React Router revalidates the route data and renders the component again. The returned object becomes actionData. After a redirect, the next page has no actionData, so it starts clean. If the user submits again, actionData is replaced with the newest result.
The sequence looks like this:
Validating with a schema library
Hand-written checks work for small forms. Larger forms are easier to maintain with a schema library such as Zod. The library gives you one place to describe the rules, and it infers the TypeScript type of the valid result.
import { z } from "zod";
export const contactSchema = z.object({
name: z.string().trim().min(1, "Name is required"),
email: z.string().trim().email("Enter a valid email address"),
});
export function parseContact(formData: FormData) {
const result = contactSchema.safeParse(Object.fromEntries(formData));
if (result.success) {
return { ok: true as const, value: result.data };
}
return {
ok: false as const,
errors: result.error.flatten().fieldErrors,
};
}safeParse returns a result object instead of throwing, which suits validation because failure is expected. fieldErrors maps each field name to an array of messages, so the component reads errors.name?.[0].
Note that Object.fromEntries(formData) keeps only the last value for repeated keys. For fields such as multiple checkboxes, use formData.getAll(name).
Distinguishing expected and unexpected failures
Not every failure is a validation error. Choose the mechanism by what the user can do about it.
| Situation | What to do | Result |
|---|---|---|
| Required field is empty | Return `data(..., { status: 400 })` | Form stays visible with messages |
| Email is already registered | Return `data(..., { status: 409 })` or 400 with a field error | Form stays visible |
| Record to update does not exist | Throw `data("Not found", { status: 404 })` | Error boundary renders |
| Database is down | Let the error propagate | Error boundary renders, status 500 |
| User is not logged in | Throw a `redirect` to the login page | Browser navigates |
Common mistakes
- Returning errors with
redirect. A redirect discards the response body. Return data instead, or store a message in a session flash if you must redirect. - Throwing for validation errors. Throwing replaces the whole route with its error boundary and the user loses their form.
- Trusting client-side checks. Always validate again in the action.
- Echoing sensitive values. Do not send passwords back in
values. Echo only fields that are safe to show again. - Using
useActionDataassumptions in typed code.actionDataisundefinedbefore the first submission, so always use optional chaining.
Client-side validation as a layer
Native attributes such as required, minLength, and type="email" still help. The browser blocks the submission before any request is made, which saves a round trip. Treat them as a convenience layered on top of server validation. They never replace it. To test the server path in the browser, add noValidate to the Form temporarily.
Exercise
A user submits the contact form with an empty name and a valid email. The action returns data({ errors: { name: "Name is required" } }, { status: 400 }). Why is it a mistake to replace this return with throw data(...), and what would the user see?
Show answer
Throwing sends control to the nearest ErrorBoundary, which replaces the route's UI. The user would lose the form and anything they typed, and they would see the error page instead of a message next to the field. Returning the data keeps the form on screen with actionData set, so the user can correct the field and resubmit.
Exercise
Your action calls formData.get("tags") for a group of checkboxes that share the name tags, but only one tag arrives. What is the cause and the fix?
Show answer
get returns only the first value for a key (and Object.fromEntries keeps only the last). Use formData.getAll("tags") to receive every selected value as an array.