Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 39 ยท Actions and Forms

Validation and Form Errors

Validate form data in React Router v7 actions, return field errors with the right status code, show them accessibly, and share a schema between client and server.

Client-side checks (required, type="email") help honest users, but they never protect your server: anyone can send a request without your form. The action must validate everything. This lesson builds a small validation pattern that returns field-level errors, displays them accessibly, and works with or without JavaScript.

The real framework code is read-only on this site. The validation functions themselves are plain JavaScript, so they run here.

A pattern: parse, collect errors, return

TSX
type Errors = Partial<Record<"title" | "price", string>>;

function validate(form: FormData) {
  const errors: Errors = {};
  const title = String(form.get("title") ?? "").trim();
  const price = Number(form.get("price"));

  if (title.length < 3) errors.title = "Title must be at least 3 characters";
  if (title.length > 80) errors.title = "Title must be at most 80 characters";
  if (!Number.isFinite(price) || price <= 0) errors.price = "Price must be a positive number";

  return { errors, values: { title, price } };
}

export async function action({ request }: Route.ActionArgs) {
  const { errors, values } = validate(await request.formData());
  if (Object.keys(errors).length > 0) {
    return data({ errors, values: { title: String(values.title), price: String(values.price) } }, { status: 400 });
  }
  await createProduct(values);
  return redirect("/products");
}

Return a 400 (or 422) status with the errors instead of throwing. Throwing a response sends the user to the error boundary, which is meant for unexpected problems, not for "the email field is empty".

JS Stand-in: collect all errors, not just the first

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

No output.

Show errors accessibly

TSX
export default function NewProduct({ actionData }: Route.ComponentProps) {
  const errors = actionData?.errors;
  return (
    <Form method="post" noValidate>
      <label htmlFor="title">Title</label>
      <input
        id="title"
        name="title"
        defaultValue={actionData?.values?.title}
        aria-invalid={errors?.title ? true : undefined}
        aria-describedby={errors?.title ? "title-error" : undefined}
      />
      {errors?.title && <p id="title-error" role="alert">{errors.title}</p>}
      ...
      <button>Create</button>
    </Form>
  );
}
  • aria-invalid and aria-describedby tell screen readers which field failed and why.
  • noValidate turns off the browser's built-in bubbles so your server-rendered messages are the single source of truth. Keep required, type and min attributes anyway if you remove noValidate on purpose for instant feedback.
  • Move focus to the first invalid field after a failed submission when JavaScript is available (a small useEffect that focuses [aria-invalid="true"]).

Use a schema library

Hand-written validators grow messy. A schema library such as Zod describes the shape once and gives typed output and messages:

TSX
import { z } from "zod";

const ProductSchema = z.object({
  title: z.string().trim().min(3, "Title must be at least 3 characters").max(80),
  price: z.coerce.number().positive("Price must be a positive number"),
});

const result = ProductSchema.safeParse(Object.fromEntries(await request.formData()));
if (!result.success) {
  return data({ errors: result.error.flatten().fieldErrors }, { status: 400 });
}
await createProduct(result.data);

Because the schema is plain code, the same file can be imported by the component for instant client-side checks, so there is one definition of "valid". Zod and similar libraries cannot run on this site, so the example is read-only; the stand-in below shows the same idea with a tiny hand-made schema.

JS Stand-in: a tiny schema shared by client and server

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

No output.

Business rules and conflicts

Some rules need the database: "this username is taken". Check inside the action and return the error against the field:

TSX
if (await usernameExists(username)) {
  return data({ errors: { username: "That username is taken" } }, { status: 409 });
}

Avoid races by also adding a unique constraint in the database and catching its error; a check followed by an insert can still collide when two requests arrive together.

Reset after success

After a successful create, redirect. A redirect loads a fresh page, so the form is empty by itself. If you stay on the page, reset an uncontrolled form with key or by calling form.reset() in an effect that watches actionData?.success.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must an action validate even if the form uses required and type=email?

    Never trust the client; the server is the only enforcement point.
  2. 2. Which is the better way to report a missing field?

    Validation failures are expected: return data, keep the user on the form.
  3. 3. What does aria-describedby do on an invalid input?

    Screen readers announce the referenced error text with the field.
  4. 4. How do you prevent two requests from creating the same username?

    Only the database can guarantee uniqueness under concurrency.

Summary

  • Validate everything on the server; client checks are for convenience.
  • Return field errors with a 400/422 status and echo the submitted values.
  • Mark invalid fields with aria-invalid and aria-describedby.
  • Share one schema between client and server; enforce uniqueness in the database.

Next: Fetchers and Concurrent Forms