Sub topic 7
Returning Validation Errors Instead of Throwing
This chapter assumes you know React function components and useState, the browser FormData API, and async functions. It also assumes you have seen the basic useActionState shape: an action that receives the previous state and a FormData, and a form wired with action={formAction}.
Why validation errors belong in state
A validation error is an expected outcome. A user typed "bob" in an email field. That is not a bug in your program. It is one of the normal results of submitting the form, like success.
useActionState is built around that idea. Whatever your action returns becomes the next state, and React re-renders with it. So the simplest way to report a validation problem is to return a value that describes it.
Throwing is for the unexpected: a crashed network, a bug, a failed assumption. When an action throws, React treats it like an error thrown during rendering. The nearest error boundary catches it and replaces part of your UI with a fallback. That is the right response to a broken server. It is the wrong response to a mistyped email.
| Situation | How to report it | Where the user sees it |
|---|---|---|
| Empty or malformed field | Return it in state | Next to the field, form stays on screen |
| Server rejects a value (for example, "email already taken") | Return it in state | Next to the field or above the form |
| Network down, unexpected exception | Let it throw | Error boundary fallback |
| Programming error | Let it throw | Error boundary fallback |
The basic pattern
The action validates the input. If something is wrong, it returns an error value and stops. If everything is fine, it does the work and returns a success value.
import { useActionState } from "react";
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) {
return { ok: false, error: "Enter a valid email address.", email };
}
await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
return { ok: true, error: null, email: "" };
}
export function SubscribeForm() {
const [state, formAction, isPending] = useActionState(subscribe, {
ok: false,
error: null,
email: "",
});
return (
<form action={formAction}>
<input name="email" type="text" defaultValue={state.email} />
<button type="submit" disabled={isPending}>
{isPending ? "Subscribing..." : "Subscribe"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.ok && <p>Thanks for subscribing.</p>}
</form>
);
}Three details matter here.
- The validation branch returns before the
fetch. No request is sent for invalid input. - Every return has the same keys:
ok,error, andemail. The component can readstate.errorwithout checking which branch ran. - The
emailvalue is returned in both branches. This is how the input keeps what the user typed. The next chapter covers that in detail, but you will see it used here already.
The input uses type="text" on purpose. With type="email", the browser would block submission and show its own message before your action runs. Browser validation is a good first layer, but your action must still validate, because users and scripts can bypass the browser.
Using `role="alert"`
The error paragraph has role="alert". Screen readers announce elements with this role when they appear. Without it, a sighted user sees the message and a screen reader user may hear nothing after pressing Submit. For field-level errors, you can also link the message to the input with aria-describedby and set aria-invalid on the input.
Field-level errors
One message is fine for one field. Real forms have several. Give the error part of your state its own shape: an object keyed by field name.
import { useActionState } from "react";
function validate(values) {
const errors = {};
if (values.name.length < 2) {
errors.name = "Name must have at least 2 characters.";
}
if (!values.email.includes("@")) {
errors.email = "Enter a valid email address.";
}
if (values.password.length < 8) {
errors.password = "Password must have at least 8 characters.";
}
return errors;
}
async function signUp(prevState, formData) {
const values = {
name: String(formData.get("name") ?? "").trim(),
email: String(formData.get("email") ?? "").trim(),
password: String(formData.get("password") ?? ""),
};
const errors = validate(values);
if (Object.keys(errors).length > 0) {
return { status: "invalid", errors, values: { name: values.name, email: values.email } };
}
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 409) {
return {
status: "invalid",
errors: { email: "That email is already registered." },
values: { name: values.name, email: values.email },
};
}
if (!response.ok) {
throw new Error("Sign-up failed.");
}
return { status: "success", errors: {}, values: { name: "", email: "" } };
}
const initialState = { status: "idle", errors: {}, values: { name: "", email: "" } };
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, initialState);
const { errors, values } = state;
return (
<form action={formAction} noValidate>
<label>
Name
<input
name="name"
type="text"
defaultValue={values.name}
aria-invalid={errors.name ? "true" : "false"}
aria-describedby={errors.name ? "name-error" : undefined}
/>
</label>
{errors.name && <p id="name-error" role="alert">{errors.name}</p>}
<label>
Email
<input
name="email"
type="email"
defaultValue={values.email}
aria-invalid={errors.email ? "true" : "false"}
aria-describedby={errors.email ? "email-error" : undefined}
/>
</label>
{errors.email && <p id="email-error" role="alert">{errors.email}</p>}
<label>
Password
<input
name="password"
type="password"
aria-invalid={errors.password ? "true" : "false"}
aria-describedby={errors.password ? "password-error" : undefined}
/>
</label>
{errors.password && <p id="password-error" role="alert">{errors.password}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Creating account..." : "Create account"}
</button>
{state.status === "success" && <p>Account created.</p>}
</form>
);
}Notes on this design:
noValidateon the form turns off the browser's built-in checks, so thetype="email"input still reaches your action and your messages are shown consistently.- The validation logic lives in a plain function,
validate. It does not touch React, so you can unit test it without rendering anything. - An empty
errorsobject means no problems. CheckingObject.keys(errors).lengthis more reliable than checking each field. - The password is never returned in state. Do not echo secrets back into the page.
- The server's 409 response is turned into a field error, because "email already taken" is something the user can fix. Any other failed response is unexpected, so the action throws.
Mixing returned errors and thrown errors
The last point is the working rule: return what the user can fix, throw what they cannot.
if (response.status === 409) {
return { status: "invalid", errors: { email: "That email is already registered." } };
}
if (!response.ok) {
throw new Error("Sign-up failed.");
}A thrown error from an action is handled by React the same way as a render error, so you need an error boundary above the form or the error propagates further up. Without a boundary, an uncaught error can unmount the whole React tree.
import { Component } from "react";
export class FormErrorBoundary extends Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
if (this.state.failed) {
return <p role="alert">Something went wrong. Please reload and try again.</p>;
}
return this.props.children;
}
}Wrap the form: <FormErrorBoundary><SignUpForm /></FormErrorBoundary>.
What happens to state between submissions
Each submission receives the state returned by the previous one as prevState. That means a returned error persists until the next submission replaces it. If the user fixes the field and submits again, your action must return an empty errors object on success, as the example does. If you forget, the old error stays on screen next to a field that is now valid.
Build each result from scratch rather than editing prevState. Returning a fresh object makes stale errors impossible, because nothing carries over by accident. Reach for prevState only when you need the earlier value, as in the shopping list example where each new item is added to the previous array.
Flow of one submission
Common mistakes
- Throwing for validation. The form disappears behind an error boundary and the user loses their input. Return the error instead.
- Returning different shapes. If one branch returns
{ error }and another returns{ errors }, the component breaks on the first unexpected path. Keep one shape, ideally with a shared initial state. - Leaving old errors in state. Always return a cleared
errorsvalue on success. - Trusting only client checks. The action runs on the client unless it is a server function. Anything security related must be checked again on the server.
- Returning secrets. State is rendered and may be visible in dev tools. Leave passwords out.
- Mutating
prevState. Treat it as read-only, as with any React state.
Exercise
A sign-up action calls the server, and the server replies with status 409 (email already registered) in one case and status 500 in another. Which case should the action return as state and which should it throw, and why?
Show answer
Return the 409 as state, for example { errors: { email: "That email is already registered." } }. The user can fix it by choosing another email, and returning keeps the form on screen with their input preserved. Throw on the 500. It is an unexpected failure the user cannot fix, so it should reach an error boundary instead of being shown as a field error.
Exercise
Your form shows "Password must have at least 8 characters." After the user types a longer password and submits successfully, the message is still on screen. What is the likely cause?
Show answer
The success branch of the action returns a state that still contains the old error, or it returns prevState unchanged. The action must return a new state with an empty errors object (or error: null) on success, because the returned value replaces the previous state completely.