State & Events
React Form Validation
Form validation in React means deriving error messages from the current form state and deciding when to show them — typically after a field is touched or after the first submit attempt, rather than while the user is still typing.
What is Form Validation in React?
Form validation in React means deriving error messages from the current form state and deciding when to show them — typically after a field is touched or after the first submit attempt, rather than while the user is still typing.
Why Form Validation matters
Validation shown too eagerly makes a form feel hostile: an email field turning red on the first character. Tracking touched fields fixes the timing without extra libraries.
Form Validation example
const [form, setForm] = useState({ email: '', phone: '' });
const [touched, setTouched] = useState({});
const errors = {
email: !form.email ? 'Email is required'
: !/\S+@\S+\.\S+/.test(form.email) ? 'Enter a valid email' : '',
phone: /^[6-9]\d{9}$/.test(form.phone) ? '' : 'Enter a valid 10-digit mobile number',
};
const isValid = Object.values(errors).every(e => !e);
<input
name="email"
value={form.email}
onChange={handleChange}
onBlur={() => setTouched(t => ({ ...t, email: true }))}
/>
{touched.email && errors.email && <small className="err">{errors.email}</small>}How this works
errors is computed during render rather than stored, so it can never fall out of sync with the values. touched only controls visibility.
Key points to remember
- Derive errors from state; do not keep them in their own state.
- Show an error after blur or after a submit attempt, not on the first keystroke.
- Validate on the server too — client validation is a convenience, not a security control.
- For large forms, React Hook Form removes most of this boilerplate.
Common mistakes with Form Validation
- Storing errors in state and forgetting to clear them when the value becomes valid.
- Trusting client-side validation as your only check.
React Form Validation— Interview Questions & FAQs
Should validation errors live in state?+
No. Compute them from the form values during render so they cannot drift out of sync. Keep only which fields have been touched, or whether submit was attempted, in state.
