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:
- User fills out the form (no validation yet)
- User clicks submit
- Your handler reads all values via refs or FormData
- You validate the values (check for empty fields, format, length, etc.)
- If valid: process/send the data
- 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.