Controlled Inputs & Validation
Using React state to power real-time form validation, conditionally render error messages, and control UI states like disabled buttons.
Real-Time Validation
Because controlled components trigger a state update on every keystroke, they provide the perfect hook for real-time validation.
Instead of waiting for the user to submit the form to tell them their password is too short, we can evaluate the input on the fly and render immediate feedback.
The Power of State
By keeping both the form data *and* the validation errors in React's state, your UI becomes purely a reflection of that state.
If errors.password exists, you render a red text box. If Object.keys(errors).length > 0, you set the submit button's disabled prop to true.
This creates a bulletproof user experience where the UI naturally prevents invalid submissions without requiring complex DOM manipulation.
Deriving Errors or Storing Them
There are two common approaches to validation in React:
1. **Derived State (On-the-fly):** You only store the form data in useState. You calculate the errors dynamically during every render based on the current data. This ensures errors are never out of sync with the data.
2. **Explicit State (On-blur / On-submit):** You store errors in their own useState. You only run the validation logic when the input loses focus (onBlur) or when the form is submitted. This is often less annoying for users (it doesn't yell at them while they are mid-sentence).
The Validation Loop
Try creating an account. Notice how the derived errors state updates on every keystroke, immediately updating the UI and disabling the submit button until all criteria are met.
Create Account
The 'errors' object is derived instantly on every render. No extra state required. The UI just conditionally renders the errors if they exist.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Validation errors can be derived directly from form state during render.
- Use conditional rendering (e.g.,
error && <span className="error">) to show messages. - Control the
disabledprop of submit buttons using the validation state. - Track
touchedstate (usually viaonBlur) to avoid prematurely yelling at users. - Complex validation is usually delegated to schema libraries like Zod.
Done with this concept?
Mark it complete to track your progress. No login needed.