How to show validation errors in React
Displaying validation errors is crucial for creating user-friendly forms that guide users to correct their input. As the creator of CoreUI, a widely used React UI library, I’ve built countless form components with robust validation error display. With over 11 years of React experience since 2014, I can tell you the most effective solution is to store error messages in state and conditionally render them. This approach provides clear feedback and improves user experience significantly.
Store validation errors in state and conditionally render them below input fields.
const [email, setEmail] = useState('')
const [errors, setErrors] = useState({})
const validateEmail = () => {
const newErrors = {}
if (!email) {
newErrors.email = 'Email is required'
} else if (!/\S+@\S+\.\S+/.test(email)) {
newErrors.email = 'Email is invalid'
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
return (
<div>
<input
type='email'
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={validateEmail}
/>
{errors.email && <span className='error'>{errors.email}</span>}
</div>
)
This code maintains an errors object in state where each field name maps to its error message. The validation function checks the input, populates the errors object if validation fails, and returns a boolean indicating success. The error message is conditionally rendered using the && operator, showing only when an error exists for that field. Validation typically runs on blur or submit events.
Best Practice Note
This is the same pattern we use in CoreUI React components to ensure consistent and accessible error display. For better user experience, consider validating on blur rather than every keystroke, and use semantic HTML with proper ARIA attributes to make errors accessible to screen readers.



