# Controlled Inputs & Validation

> Using React state to power real-time form validation, conditionally render error messages, and control UI states like disabled buttons.

Subject: React | Lesson 39 of 48 | 7 min read
Interactive lesson: https://codewithanimation.in/react/controlled-inputs-validation
Previous: [Form State Management](https://codewithanimation.in/react/form-state-management.md) | Next: [React Hook Form & Zod](https://codewithanimation.in/react/react-hook-form.md)

## 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).

## Common mistake: The 'Touched' State

A common UX pitfall of on-the-fly validation is showing an error message before the user has even finished typing.

To fix this, developers often track a `touched` state (e.g., `{ email: true, password: false }`) which gets set to true on `onBlur`. Errors are then only rendered if the field is *both* invalid *and* touched.

## Tip: Validation Libraries

Writing manual if/else statements for complex validation (regex for emails, checking if two passwords match) gets messy fast.

In the real world, developers use schema validation libraries like **Zod** or **Yup** combined with form libraries like **React Hook Form** to handle this elegantly.

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/controlled-inputs-validation

## Check yourself

### Question 1

How do you disable a submit button in React based on validation state?

- A. By using `document.getElementById('submitBtn').disabled = true` in an effect.
- B. By passing a boolean expression to the `disabled` prop: `<button disabled={hasErrors}>`
- C. By returning `false` from the `onClick` handler.

Correct answer: B

React components are declarative. You simply pass a boolean value to the HTML `disabled` prop, and React updates the DOM attribute accordingly.

### Question 2

What is the purpose of tracking the `touched` state of a form field?

- A. To prevent showing validation errors before the user has had a chance to interact with the field.
- B. To know if the form needs to be saved to the database.
- C. To automatically focus the next input field.

Correct answer: A

Without a `touched` state, on-the-fly validation will show "Email is required" the moment the page loads, which is a poor user experience.

### Question 3

If your validation logic is simple (e.g. `const isEmailValid = email.includes('@')`), where is the best place to define it?

- A. Inside a `useEffect` that updates an `isValid` state variable.
- B. Directly in the component body during render (derived state).
- C. Inside the submit handler only.

Correct answer: B

If you can calculate a value from existing state during render, you should not put it in a separate `useState` or `useEffect`. This prevents out-of-sync bugs and unnecessary re-renders.

## 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 `disabled` prop of submit buttons using the validation state.
- Track `touched` state (usually via `onBlur`) to avoid prematurely yelling at users.
- Complex validation is usually delegated to schema libraries like Zod.
