Sub topic 9
Validating form values
This chapter assumes you can build a controlled form with useState, share one change handler across several fields, and write an onSubmit handler that calls preventDefault. Here you will turn the values in state into error messages, decide when to check them, and avoid the usual mistakes. How to display those errors, track touched fields and make them accessible is covered in the next chapters. This chapter keeps the display minimal.
Validation is a function from values to errors
Validation answers one question: given the current values, what is wrong? The cleanest way to answer it is a pure function. It takes the values object and returns an errors object. A field with no entry in the object is valid.
export function validate(values) {
const errors = {};
const email = values.email.trim();
if (!email) {
errors.email = 'Email is required.';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.email = 'Enter a valid email address.';
}
if (values.password.length < 8) {
errors.password = 'Use at least 8 characters.';
}
if (values.confirm !== values.password) {
errors.confirm = 'Passwords do not match.';
}
return errors;
}
console.log(validate({ email: 'ada@', password: 'short', confirm: 'other' }));
// { email: 'Enter a valid email address.',
// password: 'Use at least 8 characters.',
// confirm: 'Passwords do not match.' }
console.log(validate({ email: '[email protected]', password: 'longenough', confirm: 'longenough' }));
// {}This design has several benefits:
- The function has no React in it, so you can test it with plain assertions.
- It returns at most one message per field. Each
ifchain checks the most basic rule first, so a blank email says "required" and not "invalid". - It can compare fields. The
confirmrule needs bothconfirmandpassword, which a per-inputonChangecheck cannot see. - Both the client and, if you share the module, a Node server can run the same rules.
Trim before checking when whitespace should not count. Trim the value you validate, and decide separately whether to trim the value you submit.
Choosing when to run validation
The function does not care when it runs. You choose the moment, and each choice changes how the form feels.
| Trigger | How it works | Trade-off |
|---|---|---|
| On change | Run on every keystroke | Instant feedback, but users see "invalid email" while still typing it |
| On blur | Run when a field loses focus | Waits until the user finishes a field, but needs per-field tracking (touched state) |
| On submit | Run when the form is submitted | Simplest, but users learn about all problems at once, late |
A common compromise is to validate on submit first. After the first failed attempt, re-validate on every change, so errors disappear as soon as the user fixes them. Blur-based validation needs the touched-field tracking described in the next chapter.
Derive errors during render
The first example in this tutorial's code stored errors in state with setErrors(validate(values)). That works for a submit-only form. For anything beyond that, there is a simpler pattern. Errors are a pure function of values, so compute them during render instead of storing them.
import { useState } from 'react';
import { validate } from './validate';
export default function SignupForm() {
const [values, setValues] = useState({ email: '', password: '', confirm: '' });
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 handleSubmit(e) {
e.preventDefault();
setSubmitted(true);
if (!isValid) return;
console.log('Valid', values);
}
const fields = [
{ name: 'email', label: 'Email', type: 'email' },
{ name: 'password', label: 'Password', type: 'password' },
{ name: 'confirm', label: 'Confirm password', type: 'password' },
];
return (
<form onSubmit={handleSubmit} noValidate>
{fields.map(({ name, label, type }) => (
<div key={name}>
<label htmlFor={name}>{label}</label>
<input
id={name}
name={name}
type={type}
value={values[name]}
onChange={handleChange}
/>
{submitted && errors[name] && <p role="alert">{errors[name]}</p>}
</div>
))}
<button type="submit">Create account</button>
</form>
);
}errors is recalculated on every render, so it can never be stale. There is no useEffect that syncs errors to values, and no moment when the two disagree. The submitted flag only controls visibility. Once the user has tried to submit, errors appear and then update live as they type.
Derived errors also give you isValid for free. You can use it to disable the submit button, though many designers advise against that. A disabled button gives no explanation, while a submit that shows messages does.
Stored errors, and when they are still needed
Derived errors cover every rule that can be checked from the current values. Some errors cannot be derived, because they come from outside the form:
- A server response such as "That email is already registered."
- An async check, such as username availability.
Keep these in a separate state variable, for example serverErrors, and merge them when displaying: const shown = { ...serverErrors, ...errors }. Clear the matching serverErrors entry in handleChange, because the old message is about a value the user has since changed.
For async checks on change, ignore stale responses. If the user types "ab" then "abc", the answer for "ab" can arrive after the answer for "abc". Debounce the request and discard any response whose value no longer matches the current one. Never rely on client validation alone for rules that protect data. The server must repeat every check, because anyone can send a request without your form.
Browser validation and `noValidate`
HTML has its own constraint validation: required, type="email", minLength, pattern. When a form has these attributes, the browser blocks submission and shows its own bubble. That bubble is hard to style, differs between browsers, and can appear before your onSubmit runs at all.
You have two reasonable choices:
- Add
noValidateto the<form>and own all validation in React. The examples above do this, which gives consistent messages and styling. - Keep the browser rules and treat your function as a second layer. This is less code, but you give up control over wording and timing.
Whichever you choose, keep the HTML attributes that carry meaning. type="email" still brings the right mobile keyboard, and required still communicates intent to assistive technology, even with noValidate set.
Common errors
- Validating the old value. Inside
handleChange,valuesis still the value from before the update. If you need to validate the new value there, build it first (const next = { ...values, [name]: value }) and validatenext. - Checking
errors.email === undefinedfor one field butObject.keys(errors).lengthfor the form. Both are fine, but keep the contract that an invalid field has an entry and a valid one has none. Do not store empty strings for valid fields, orObject.keys(errors).length === 0will always be false. - Number inputs.
e.target.valueis always a string, even fortype="number". Compare withNumber(value)and handle the empty string, sinceNumber('')is0. - Forgetting to stop on failure. Setting errors but not returning from
handleSubmitstill sends the invalid data. - Validating only in the UI. Disabling a button or hiding a field does not prevent a bad request.
- Over-strict rules. Email regexes cannot fully match the real address format. A loose check for text, then
@, then text with a dot is enough. Confirm real addresses by sending a message to them.
Exercise
In the SignupForm component, the user types a valid password and a matching confirmation, then edits the password by one character. Without any extra code, which error appears and why?
Show answer
The "Passwords do not match." error appears on the confirm field once the form has been submitted (or immediately, if you display errors without a submitted flag). Errors are derived from the current values on every render, and the confirm rule compares both fields, so changing the password re-runs the rule and the mismatch is detected without any additional handler.
Exercise
Add a rule to validate so that the password must contain at least one digit, and explain why you should not also store the result in a separate errors state variable.
Show answer
Add this inside validate, after the length check: else if (!/\d/.test(values.password)) errors.password = 'Include at least one number.'; (chained so the length message takes priority). Errors are a pure function of values, so a separate state variable duplicates information that can already be computed. It would also need to be updated every time values change, and the two could fall out of sync for a render.