Sub topic 10
Showing errors and tracking touched fields
This chapter assumes you can write function components with useState, you know how a controlled input works, and you have a pure validate(values) function that returns an errors object, as in the previous chapter. Here you decide when those errors appear on screen.
Validating is not the same as showing
Running validate on every render is cheap and always correct. Showing every error immediately is a different matter. On a fresh sign-up form, every field is empty and therefore invalid. If you render all the errors at once, the user sees a wall of red before typing a character.
Keep two ideas apart:
- Validity is a fact about the current values. You can compute it at any time.
- Visibility is a decision about which errors the user should see right now.
The usual approach is to compute errors from values during render, then filter them through a second piece of state that records what the user has interacted with.
When to reveal an error
There are three common timing strategies.
| Strategy | Error appears | Trade-off |
|---|---|---|
| On submit only | After the first submit attempt | Simple, but feedback comes late |
| On change | After every keystroke | Noisy, because the user is told "invalid email" after typing one character |
| On blur, after touched | When the user leaves the field | Feedback arrives when the user has finished the field |
A field is touched when the user has focused it and then left it. The blur event fires at that moment, so onBlur is where you record it. After a submit attempt, treat every field as touched, so that a user who never visited a field still sees its error.
Derive errors, store touched
A common mistake is to keep errors in state and update it inside handleChange. That works, but the errors can drift out of sync with the values, for example when a value is changed by a reset or by code other than the change handler. A safer design stores only the raw facts (values and touched) and derives the rest.
import { useState } from 'react';
function validate(values) {
const errors = {};
if (!values.email.includes('@')) {
errors.email = 'Enter a valid email address.';
}
if (values.password.length < 8) {
errors.password = 'Use at least 8 characters.';
}
return errors;
}
export default function LoginForm() {
const [values, setValues] = useState({ email: '', password: '' });
const [touched, setTouched] = useState({});
const [submitted, setSubmitted] = useState(false);
const errors = validate(values);
const isValid = Object.keys(errors).length === 0;
function handleChange(e) {
const { name, value } = e.target;
setValues((prev) => ({ ...prev, [name]: value }));
}
function handleBlur(e) {
const { name } = e.target;
setTouched((prev) => ({ ...prev, [name]: true }));
}
function handleSubmit(e) {
e.preventDefault();
setSubmitted(true);
if (isValid) {
console.log('Valid', values);
}
}
function showError(name) {
return (touched[name] || submitted) && errors[name];
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
aria-invalid={Boolean(showError('email'))}
aria-describedby={showError('email') ? 'email-error' : undefined}
/>
{showError('email') && <p id="email-error">{errors.email}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
aria-invalid={Boolean(showError('password'))}
aria-describedby={showError('password') ? 'password-error' : undefined}
/>
{showError('password') && <p id="password-error">{errors.password}</p>}
<button type="submit">Log in</button>
</form>
);
}Three details are worth reading closely.
errorsis a plainconstcomputed in the render body. It is never stale, because it is recomputed whenevervalueschanges.showErrorcombines the two sources: an error is visible only if the field is touched or a submit was attempted.onBluris passed the same shared handler pattern asonChange, and it reads the field key fromname.
React's onBlur is attached to the focusout event, so it bubbles. That means you could place a single onBlur on the <form> element and catch every field, but the explicit per-field handler is easier to follow.
The flow of a single field
The key point is that ShowingError is not stored anywhere. It is the result of touched || submitted combined with errors[name].
Tracking touched with a single object
touched has the same shape as values, with booleans instead of strings. Using a keyed object means you do not need one useState per field. Two behaviors to know:
- A field missing from
touchedreads asundefined, which is falsy, so you do not have to initialize every key. - The
submittedflag avoids a loop over all field names. If you prefer to avoid the second flag, you can mark every field inhandleSubmitinstead:
function handleSubmit(e) {
e.preventDefault();
const allTouched = Object.keys(values).reduce(
(acc, key) => ({ ...acc, [key]: true }),
{}
);
setTouched(allTouched);
if (isValid) {
console.log('Valid', values);
}
}Both work. The single submitted flag is shorter. The allTouched version keeps one source of truth, which matters if you later add a "reset touched" action.
Edge cases
Checkboxes and selects have no meaningful blur
A checkbox that must be ticked ("I accept the terms") can be touched by focusing it and tabbing away, but most users click it. Waiting for blur means the error may linger after they tick it, or never show until submit. For these controls, it is common to rely on the submit attempt only, or to mark the field touched in onChange.
Errors for fields the user has not reached yet
With blur-based timing, a user filling the form top to bottom only sees errors for fields they have left. Fields below stay quiet until submit. That is the intended behavior.
Re-validating after the first error
Once an error is visible, the user needs fast feedback that they fixed it. Because errors is derived on each render, the message disappears on the first keystroke that makes the value valid. You get this behavior for free. If you had stored errors in state and only updated them on blur, the message would persist until the next blur, which feels broken.
Focusing the first invalid field
After a failed submit, keyboard and screen reader users benefit from having focus moved to the first invalid input. Use a ref per field, or look the element up by id:
function handleSubmit(e) {
e.preventDefault();
setSubmitted(true);
const firstInvalid = Object.keys(errors)[0];
if (firstInvalid) {
document.getElementById(firstInvalid)?.focus();
return;
}
console.log('Valid', values);
}This relies on each input's id matching its key in errors, which is true in the form above. The lookup happens in an event handler, after the DOM exists, so it is safe.
Server errors
Client-side validation cannot catch everything. A server may reject an email as already registered. Store those messages in separate state, for example serverErrors, and merge them at display time: errors[name] ?? serverErrors[name]. Clear a field's server error in handleChange for that field, because the old message describes the old value.
Common mistakes
- Showing errors on first render. The cause is ignoring
touched. Gate every message behindtouched[name] || submitted. - Storing errors in state and forgetting to recompute them. The message becomes stale after a reset or a programmatic change. Derive errors from values instead.
- Using
onFocusinstead ofonBlur. Marking a field touched on focus shows the error the moment the user clicks into an empty field. - Disabling the submit button until the form is valid. The user then gets no explanation of why the button does nothing. Keep the button enabled and show errors on submit.
- Setting
aria-describedbyto an id that is not in the DOM. Only point at the error element when it is rendered, as the code above does.
Exercises
Exercise
In the form above, a user types "abc" into the email field, clicks into the password field without typing, and then clicks the Log in button. Which error messages are visible after the click, and why?
Show answer
Both. The email error is visible because email was touched when the user left it, and the password error is visible because it was touched on blur and because submitted became true. Both values are invalid, so both messages render.
Exercise
Why is it safer to compute errors with const errors = validate(values) during render than to store errors in state and update it in handleChange?
Show answer
A derived value is recomputed whenever values changes, so it cannot disagree with the current values. Stored errors can go stale when values change another way, such as a form reset, or when the handler that updates them is skipped.
Exercise
A "Remember me" checkbox is optional, but an "Accept terms" checkbox is required. How would you decide when to show the terms error, and why is blur a poor trigger?
Show answer
Show it after a submit attempt, or mark the field touched in its onChange handler. Blur is a poor trigger because most users click a checkbox and never tab away from it, so the field may not register as touched until much later.