How would you validate a form in React and show an error message to the user?
Short answer
You keep track of any validation errors in state alongside your form values, and check the input against your rules either as the user types or when they try to submit. If a rule fails, you update the error state and display a message near the relevant field.
Advertisement
AModel answer
You keep track of any validation errors in state alongside your form values, and check the input against your rules either as the user types or when they try to submit. If a rule fails, you update the error state and display a message near the relevant field.
function SignupForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
function handleSubmit(e) {
e.preventDefault();
if (!email.includes('@')) {
setError('Please enter a valid email address');
return;
}
setError('');
submitForm(email);
}
return (
<form onSubmit={handleSubmit}>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit">Sign Up</button>
</form>
);
}Real-world example
A signup form shows a clear red error message right below the email field the moment a user tries to submit an invalid email address, instead of silently doing nothing or crashing.
Likely follow-ups
- How would you validate multiple fields at once and track separate errors for each?
- What is the benefit of using a form library like React Hook Form instead of writing this by hand?
Related topics