🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Forms: Controlled Inputs, Validation, and Libraries

React FormsFormsđŸŸĸ Free Lesson

What You'll Learn

  • 1Explain the difference between controlled and uncontrolled inputs and when each fits
  • 2Write a controlled form with per-field validation and accessible error messages
  • 3Submit uncontrolled forms with FormData and progressive enhancement in mind
  • 4Decide whether a form library or a multi-step wizard needs custom state

Two ways to own the data

Every form has the same job: collect values, check them, and hand them somewhere. React offers two ownership models, and the choice is about where the source of truth lives.

A controlled input keeps its value in React state. The input's value prop is set from that state, and every keystroke routes through a change handler that updates it. Because the value is always available to your code, you can format as the user types, disable submit until the form is valid, or show a live preview beside the field. The contract is strict: if you set value, you must also supply onChange, otherwise the field appears frozen.

An uncontrolled input lets the DOM own the value. You read it on submit from a ref, from the form element, or from the FormData constructor. React gets out of the way between keystrokes, which makes long text areas and native-heavy forms simpler, and it degrades gracefully when JavaScript fails to load.

A controlled form with real validation

Validation in a controlled form is ordinary logic. Keep an errors object next to the values, validate on submit, and optionally revalidate a field after its first error so the message clears as soon as the user corrects it.

function SignupForm({ onCreate }) {
  const [values, setValues] = useState({ email: '', password: '', plan: 'free' });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});

  const validate = (next) => {
    const found = {};
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(next.email)) {
      found.email = 'Enter a valid email address';
    }
    if (next.password.length < 8) {
      found.password = 'Use at least 8 characters';
    }
    return found;
  };

  const update = (field) => (event) => {
    const next = { ...values, [field]: event.target.value };
    setValues(next);
    if (touched[field]) setErrors(validate(next));
  };

  const onSubmit = (event) => {
    event.preventDefault();
    const found = validate(values);
    setErrors(found);
    setTouched({ email: true, password: true, plan: true });
    if (Object.keys(found).length === 0) onCreate(values);
  };

  return (
    <form onSubmit={onSubmit} noValidate>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        type="email"
        value={values.email}
        onChange={update('email')}
        onBlur={() => setTouched((t) => ({ ...t, email: true }))}
        aria-invalid={Boolean(errors.email)}
        aria-describedby={errors.email ? 'email-error' : undefined}
      />
      {errors.email && <p id="email-error" role="alert">{errors.email}</p>}

      <label htmlFor="password">Password</label>
      <input
        id="password"
        type="password"
        value={values.password}
        onChange={update('password')}
        aria-invalid={Boolean(errors.password)}
        aria-describedby={errors.password ? 'password-error' : undefined}
      />
      {errors.password && <p id="password-error" role="alert">{errors.password}</p>}

      <button type="submit">Create account</button>
    </form>
  );
}

The aria-describedby wiring is not decoration. Screen readers announce the description alongside the field, so a sighted user sees the red text and a screen reader user hears it when focus lands on the input.

Uncontrolled inputs and FormData

When the form does not need live validation, uncontrolled inputs reduce the code substantially. The modern browser's FormData constructor reads every named control without manual ref juggling.

function FeedbackForm({ onSubmit }) {
  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const payload = {
      rating: Number(data.get('rating')),
      topic: data.get('topic'),
      comments: String(data.get('comments') || '').trim(),
      subscribe: data.get('subscribe') === 'on',
    };
    if (!payload.comments) {
      event.currentTarget.elements.comments.focus();
      return;
    }
    onSubmit(payload);
    event.currentTarget.reset();
  };

  return (
    <form onSubmit={handleSubmit}>
      <select name="topic" defaultValue="product">
        <option value="product">Product</option>
        <option value="billing">Billing</option>
      </select>
      <input name="rating" type="number" min="1" max="5" defaultValue="3" />
      <textarea name="comments" rows="4" />
      <label>
        <input name="subscribe" type="checkbox" />
        Email me a copy
      </label>
      <button type="submit">Send feedback</button>
    </form>
  );
}

Note the small details that prevent surprises: every control carries a name attribute, defaults are expressed as props rather than as state, and the form resets itself after a successful submit by calling reset on the element rather than by rewriting each field.

Choosing a validation approach

Validation has several dimensions, and mixing them without a plan produces contradictory messages that appear and disappear at confusing times.

ApproachBest forCost
Validate on submit onlyShort forms with few fieldsUsers discover problems late, at the worst moment
Revalidate a field after its first errorMost interactive formsA little extra state, a much calmer experience
Validate on every keystrokeNumeric ranges and format masksEarly noise while typing, so gate it behind first touch
Schema library such as Zod or YupForms shared with the serverOne schema to maintain, but it must track the API
Native constraint validationSimple cases where DOM rules sufficeLimited styling control, inconsistent across browsers

The pragmatic default is submit-time validation plus revalidation after blur, which balances early feedback with the user's right to type a half-finished email address without being scolded.

Numbers, dates, and values that arrive as strings

Every control hands you text, and converting it carelessly is a quiet source of bugs. A number field with an empty value yields an empty string, which becomes zero after an unchecked cast, which then fails a minimum check in a way that looks like a validation bug rather than a parsing one. Coerce at the boundary, immediately after reading the field, and let the rest of the form work with real types.

Date inputs deserve the same treatment. The browser returns an ISO date string, but comparisons, formatting, and time zones all behave differently from what a naive new Date call suggests. Parse explicitly, decide whether the value is a calendar date or an instant in time, and keep that decision in one helper so every form agrees.

For formatted input such as currency or phone numbers, keep two representations: the raw string the user typed and the normalised value you will submit. Edit the display value as they type, derive the normalised one on change, and validate the normalised one. Fighting the caret position while reformatting the same field is possible, but it belongs in a tested helper or a library, not inline in a component's change handler.

When a form library earns its place

React Hook Form and Formik exist to reduce the re-render cost of controlled forms and to centralise registration. React Hook Form in particular subscribes per field, so typing in one input does not re-render the entire form, and its register helper wires refs for you.

import { useForm } from 'react-hook-form';

function ContactForm({ onSend }) {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({ mode: 'onBlur' });

  return (
    <form onSubmit={handleSubmit(onSend)} noValidate>
      <input
        {...register('name', { required: 'Name is required' })}
        aria-invalid={Boolean(errors.name)}
      />
      {errors.name && <p role="alert">{errors.name.message}</p>}

      <input
        type="email"
        {...register('email', {
          required: 'Email is required',
          pattern: { value: /^\S+@\S+\.\S+$/, message: 'Invalid email' },
        })}
      />
      {errors.email && <p role="alert">{errors.email.message}</p>}

      <button type="submit" disabled={isSubmitting}>Send</button>
    </form>
  );
}

Reach for it once a form has more than about eight fields, nested objects, array fields such as multiple addresses, or server-side error mapping. Below that threshold, plain state is fewer moving parts and easier to hand to the next developer.

Multi-step forms without losing work

A wizard is one form spread across several screens. The classic bug is storing each step in local state inside the step component, so navigating backwards remounts the component and the data vanishes. Keep the accumulated values at the wizard level, validate each step on next, and treat the whole thing as a single submit at the end.

Preserve the draft as well. Writing the values to session storage on every change, or on blur if keystroke writes feel heavy, means a refresh or a closed tab does not cost the user their typing. Clear the draft only after the server confirms the final submit, never before.

Submitting, and mapping server errors back to fields

The client and the server usually disagree about what a valid form is, and the user experiences that disagreement as a confusing failure. Client validation is a courtesy that saves a round trip; the server remains the authority on uniqueness, entitlements, and business rules. Design your submit path so the server's answers land in the same errors object the client already renders.

A useful shape is to treat the response as either a value or a map of field-level problems. On failure, merge that map into the errors state, mark the affected fields as touched so their messages are visible, and move focus to the first invalid control. A response that has no field attached, such as a rate limit or an expired session, belongs in a form-level banner rather than under any single input.

Keep the form usable while the request is in flight. Disable the submit button, keep the values mounted so the user can read what they typed, and never clear the form until the server confirms success. If the request fails, the worst possible outcome is an empty form and an error message; the second worst is a double submit that created two orders. Both are preventable with a single isSubmitting flag and a guard in the handler.

Common Mistakes

Setting value on an input without supplying onChange, leaving the field stuck

Fix: Either control the input completely or leave it uncontrolled and read it on submit

Clearing all errors on every keystroke so messages flash while the user types

Fix: Validate on submit and revalidate a field only after it has been touched once

Storing each wizard step in its own component state

Fix: Lift the draft to the wizard root and persist it so navigation cannot lose data

Showing errors only with color, with no text and no programmatic link

Fix: Render a message, connect it with aria-describedby, and mark the field aria-invalid

Best Practices

  • Give every input a label tied by htmlFor or by wrapping the control
  • Use noValidate on forms you validate yourself so browser bubbles do not fight your messages
  • Disable the submit button while a request is in flight to prevent double posts
  • Mirror server-side field errors into the same errors object used by client validation
  • Reset the form through the element after success rather than by resetting each field by hand

Key Takeaways

  • Controlled inputs give you the value on every keystroke; uncontrolled inputs give you the value on submit
  • FormData reads named controls without manual refs and keeps the code short
  • Validate on submit, then revalidate a field once it has been touched
  • Form libraries pay off above roughly eight fields, or with nested and array data
  • Multi-step forms must keep their draft at the wizard level and persist it across navigation
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement