React5 min read
React Form Validation
Validate forms and show error messages in React.
Sarah Johnson
December 20, 2025
0.0k0
Learn to validate forms and show errors.
Basic Validation
function LoginForm() {
const [email, setEmail] = useState('');
const [errors, setErrors] = useState({});
const validate = () => {
const newErrors = {};
if (!email) {
newErrors.email = 'Email required';
} else if (!/\S+@\S+\.\S+/.test(email)) {
newErrors.email = 'Email invalid';
}
return newErrors;
};
const handleSubmit = (e) => {
e.preventDefault();
const newErrors = validate();
if (Object.keys(newErrors).length === 0) {
// Submit form
} else {
setErrors(newErrors);
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={email}
onChange={e => setEmail(e.target.value)}
/>
{errors.email && <p style={{color: 'red'}}>{errors.email}</p>}
<button type="submit">Submit</button>
</form>
);
}
Real-time Validation
const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');
const handleEmailChange = (e) => {
const value = e.target.value;
setEmail(value);
if (!value) {
setEmailError('Email required');
} else if (!/\S+@\S+\.\S+/.test(value)) {
setEmailError('Email invalid');
} else {
setEmailError('');
}
};
Remember
- Validate on submit
- Show clear error messages
- Disable submit if errors
- Use regex for patterns
Next: Learn lazy loading!
#React#Forms#Validation#Intermediate