Adding Validation
Validation in a React form means checking what the user typed, deciding whether it is acceptable, and showing a helpful message when it is not, before the data is sent anywhere. You add it so users can correct mistakes like an empty name or an email without an "@" straight away, instead of waiting for a server error.
When to validate: submit, blur or keystroke
There are three common moments to run checks, and good forms usually combine them:
| Moment | Good for | Drawback |
|---|---|---|
| On submit | A final check of every field | Errors appear late |
| On blur (leaving a field) | Telling users once they finish a field | Needs a "touched" flag per field |
| On every keystroke | Clearing an error as soon as it is fixed | Shouting at users who have only typed one letter |
A friendly pattern is: show an error only after a field has been touched, then update it live while the user types.
Deriving validity instead of storing it
You do not need a separate state for "is the email valid". It can be calculated from the value on every render. Only the raw values and whether each field was touched need to live in state.
import { useState } from 'react';
function SignupForm() {
const [email, setEmail] = useState('');
const [touched, setTouched] = useState(false);
const emailIsValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
const showError = touched && !emailIsValid;
function handleSubmit(e) {
e.preventDefault();
setTouched(true);
if (!emailIsValid) return;
console.log('Sending', email.trim());
setEmail('');
setTouched(false);
}
return (
<form onSubmit={handleSubmit} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={() => setTouched(true)}
aria-invalid={showError}
aria-describedby="email-error"
/>
{showError && (
<p id="email-error">Please enter a valid email address.</p>
)}
<button type="submit">Sign up</button>
</form>
);
}
Because emailIsValid is computed, it can never fall out of sync with the input. Storing it in state as well would create two sources of truth that can disagree.
Checking the whole form
With several fields, combine the individual results into one value such as const formIsValid = nameIsValid && emailIsValid. You can use it to block submission or to disable the submit button. Disabling is common, but it can confuse users who do not know why the button is grey, so make sure the errors are visible too.
When the same pattern repeats for every field, it is a sign to move it into a custom hook, which is exactly where the next lesson goes.
Pitfalls to avoid
- Trusting client-side checks. Anyone can bypass JavaScript or send requests directly. Validation in the browser is for user experience; the server must validate again.
- Forgetting to trim. A name made only of spaces passes a simple "not empty" check. Use
value.trim() !== ''. - Errors on page load. Showing red messages before the user has typed anything feels hostile. That is what the touched flag prevents.
- Not resetting touched. After a successful submit, clear both the value and the touched flag, or an error flashes on the now-empty field.
Built-in HTML validation
Attributes like required, type="email" and minLength give free browser checks. Many React forms add noValidate to the form, as above, to turn off the browser's popups and show consistent custom messages instead, while keeping those attributes for meaning.
Keep this in mind: store values and touched flags, compute validity, show errors only after interaction, and always validate again on the server.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.