Sub topic 3
Showing Errors and Tracking Touched Fields
Assume you know JavaScript objects, React components, JSX, props, and basic HTML forms. This chapter focuses on the decisions around validation and form state.
Showing errors and tracking touched fields
An error tells the user what is invalid. A touched flag tells you whether the user has interacted with a field. Showing errors only for touched fields prevents an empty form from displaying a wall of warnings.
import { useState } from 'react';
function validate(values) {
const errors = {};
if (!values.email.includes('@')) errors.email = 'Enter a valid email.';
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 [errors, setErrors] = useState({});
function handleChange(e) {
setValues((old) => ({ ...old, [e.target.name]: e.target.value }));
}
function handleBlur(e) {
const nextTouched = { ...touched, [e.target.name]: true };
setTouched(nextTouched);
setErrors(validate(values));
}
function handleSubmit(e) {
e.preventDefault();
const nextErrors = validate(values);
setErrors(nextErrors);
setTouched({ email: true, password: true });
}
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(touched.email && errors.email)}
aria-describedby={touched.email && errors.email ? 'email-error' : undefined}
/>
{touched.email && errors.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(touched.password && errors.password)}
aria-describedby={touched.password && errors.password ? 'password-error' : undefined}
/>
{touched.password && errors.password && (
<p id="password-error">{errors.password}</p>
)}
<button type="submit">Log in</button>
</form>
);
}Accessible labels and error messages
A <label> connected with htmlFor gives the input an accessible name. aria-invalid identifies an invalid field. aria-describedby connects that field to its specific error message, so assistive technology can read the context.
Initial values and resetting a form
Keep initial values in one object. Reset controlled fields by restoring that object.
const initialValues = { email: '', password: '' };
const [values, setValues] = useState(initialValues);
function resetForm() {
setValues(initialValues);
setTouched({});
setErrors({});
}A changing key can also recreate a form when editing a different record. Use this when the new record should receive fresh initial state.
File inputs
File inputs are always uncontrolled for security reasons. Read the selected file from event.target.files or a ref. Do not set a file input's value from React state.
> callout note > Validate file type and size on the server too. Client-side checks improve feedback but cannot enforce security.
Re-rendering cost
Controlled inputs update React state on every keystroke. This is usually fine. For very large forms, expensive parent rendering can make typing slow. Keep state near the form, split expensive components, or use an uncontrolled approach when live values are unnecessary.
Choosing a form approach
| Situation | Suitable approach |
|---|---|
| A few fields with custom behavior | Hand-written controlled form |
| Many fields, repeated validation, and complex submission state | Form library |
| Simple search or filter form | Uncontrolled form with `FormData` |
A library can manage touched state, errors, validation, and performance. It also adds dependencies and conventions. Choose one when it removes repeated complexity, not merely because the form has several fields.
Exercise
When should a validation error usually become visible?
Show answer
After the field is touched or after submission, so untouched fields do not show premature warnings.