Sub topic 9
Validating Form Values
This chapter assumes you can write function components, use useState, and handle onChange and onSubmit events. It also assumes you know how to keep several fields in one state object, as covered in earlier chapters.
What validation means here
Validation checks whether the values a user entered are acceptable before you use them. In a controlled form, the values already live in state, so validation is a plain function: values go in, a list of problems comes out.
Keep that function pure. It should not read the DOM, set state, or call the network. A pure function is easy to test and easy to reuse on submit, on blur, or on the server.
A pure validate function
The function below returns an object. Each key is a field name, and each value is an error message. An empty object means the values are valid.
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 [errors, setErrors] = useState({});
function handleChange(e) {
setValues((prev) => ({ ...prev, [e.target.name]: e.target.value }));
}
function handleSubmit(e) {
e.preventDefault();
const nextErrors = validate(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
console.log('Valid', values);
}
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
<label htmlFor="password">Password</label>
<input
id="password"
name="password"
type="password"
value={values.password}
onChange={handleChange}
/>
{errors.password && <p>{errors.password}</p>}
<button type="submit">Log in</button>
</form>
);
}Three details matter here:
handleSubmitcallse.preventDefault()so the browser does not reload the page.validateruns on the currentvalues, and its result is stored withsetErrorsso the screen can show it.noValidateon the form turns off the browser's built-in bubbles. Without it, the browser may block submit with its own messages before your handler runs.
The flow on submit
Choosing when to validate
You can run validate at different moments. Each has a trade-off.
| Moment | Benefit | Cost |
|---|---|---|
| On submit | Simple, never nags the user | Errors appear all at once, late |
| On blur (field loses focus) | Feedback after the user finishes a field | Needs tracking of which fields were visited |
| On every change | Immediate feedback | Shows errors before the user has finished typing |
A common compromise is to validate on submit first, then re-validate as the user edits. Another is to track a "touched" flag per field so errors only appear for fields the user has already left.
Derive errors instead of storing them
Storing errors in state works, but it can go stale. If the user fixes a field after a failed submit, the old message stays until the next submit. You can avoid this by computing errors during render:
const errors = validate(values);
const isValid = Object.keys(errors).length === 0;Because errors are derived from values, they can never disagree with the inputs. Pair this with a submitted or touched flag so you control when messages are displayed.
Common errors
- Forgetting
preventDefault. The page reloads and state is lost. - Validating stale values. Inside an event handler, use the
valuesfrom the current render, not a value you just passed to a state setter. The setter does not change the variable until the next render. - Trusting only the client. Client checks improve the experience, but users can bypass them. Always validate again on the server.
- Messages that are only visual. Errors must also reach assistive technology, which a later chapter covers.
Exercise
A user submits the login form with an empty email, fixes it, and the old error message still shows until they submit again. What causes this, and how can you change the code so it cannot happen?
Show answer
The errors are stored in state with setErrors, and they are only updated inside handleSubmit, so editing a field does not refresh them. Compute the errors during render with const errors = validate(values) (optionally gated by a touched or submitted flag). The errors are then always derived from the current values.