Sub topic 11
Validating input and returning errors
This chapter assumes you know HTML forms, FormData, HTTP status codes, and the basics of route action functions and Form from the previous chapter. It covers how an action rejects bad input and how the component shows the problem.
Why validate in the action
Browser attributes such as required help users, but anyone can bypass them with a direct request. The action runs on the server, so it is the place where validation must happen. Client-side checks are only a convenience.
The pattern has three steps:
- Read and clean the submitted values.
- If any value is invalid, return the errors with a 400 status.
- If everything is valid, perform the mutation and redirect.
Returning (not throwing) the errors keeps the user on the same page with their form still in view. Throwing is for unexpected failures, which the error boundary handles.
Returning errors with `data`
The data helper attaches a status code to a plain object. The object becomes actionData in the component.
import { Form, data, redirect } from "react-router";
import type { Route } from "./+types/new";
import { createContact } from "~/contacts.server";
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: { name?: string; email?: string } = {};
if (!name) errors.name = "Name is required";
if (!email.includes("@")) errors.email = "Enter a valid email address";
if (errors.name || errors.email) {
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={Boolean(errors?.name)} />
</label>
{errors?.name ? <p role="alert">{errors.name}</p> : null}
<label>
Email
<input name="email" defaultValue={values?.email} aria-invalid={Boolean(errors?.email)} />
</label>
{errors?.email ? <p role="alert">{errors.email}</p> : null}
<button type="submit">Save</button>
</Form>
);
}Three details matter here:
formData.getreturnsFormDataEntryValue | null, which can also be aFile. Wrapping it inString(... ?? "")gives you a string to trim and test.- The action returns the submitted
valuesso the form can refill itself withdefaultValue. Without this, the user retypes everything after an error. - The 400 status tells HTTP clients the request was invalid. React Router still renders the same route, now with
actionDataset.
The request flow
Common errors
- Throwing instead of returning. A thrown 400 response reaches the error boundary and replaces the whole route with an error page. Return field errors instead.
- Forgetting that
actionDataisundefinedbefore the first submit. Use optional chaining, as inactionData?.errors. - Trusting only client checks. Always repeat the checks in the action.
- Returning raw
FormDataorFileobjects.actionDatamust be serializable, so return plain strings and objects.
Exercise
Why does the action in this chapter return data({ errors, values }, { status: 400 }) instead of throwing it, and why is values included?
Show answer
Returning keeps the user on the same route with the form visible, so the component can show field-level messages through actionData. Throwing would trigger the error boundary and replace the page. Including values lets the inputs refill with defaultValue, so the user does not retype what they entered.