Course contentsShow
← React
Lesson 520 of 2,39614. Uncontrolled ComponentsFree lesson

Combining Uncontrolled Inputs with Validation

Validate uncontrolled input values after reading them on submit before processing or sending data.

Combining Uncontrolled Inputs with Validation

You'll learn how to validate data from uncontrolled inputs after reading their values, before processing or sending.

The Core Idea

Uncontrolled components don't give you live feedback as users type, but you still need to validate their data before doing anything with it. The solution: read the values on submit (using refs or event.target.elements), then run your validation checks before processing.

Think of it like a security checkpoint at an airport. Passengers (input values) move freely until they reach the gate (form submission), where everything gets checked before they board the plane (data gets processed).

The Pattern

Here's the flow:

  1. User fills out the form (no validation yet)
  2. User clicks submit
  3. Your handler reads all values via refs or FormData
  4. You validate the values (check for empty fields, format, length, etc.)
  5. If valid: process/send the data
  6. If invalid: show error messages and prevent submission
function RegistrationForm() {
  const emailRef = useRef();
  const passwordRef = useRef();
  const [errors, setErrors] = useState({});

  function handleSubmit(e) {
    e.preventDefault();
    
    const email = emailRef.current.value;
    const password = passwordRef.current.value;
    const newErrors = {};

    // Validation logic
    if (!email.includes('@')) {
      newErrors.email = 'Invalid email';
    }
    if (password.length < 8) {
      newErrors.password = 'Must be 8+ characters';
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return; // Stop here, don't submit
    }

    // All valid - process data
    console.log('Submitting:', { email, password });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input ref={emailRef} defaultValue="" />
      {errors.email && <span>{errors.email}</span>}
      
      <input ref={passwordRef} type="password" defaultValue="" />
      {errors.password && <span>{errors.password}</span>}
      
      <button type="submit">Register</button>
    </form>
  );
}

Key Takeaway: Uncontrolled inputs can still be validated—just do it at submission time by reading values first, checking them, and only proceeding if they pass your rules.