React - Text Inputs & Validation
Overview
Estimated time: 20–30 minutes
Learn how to add text fields, read values, and implement simple validation patterns in React using controlled inputs.
Learning Objectives
- Create controlled text inputs and read their values.
- Validate input on change and on submit.
- Display validation messages and prevent invalid submit.
Prerequisites
- HTML, CSS, JavaScript (ES6+)
Try it: Name with Validation
View source
const { useState } = React;
function NameForm(){
  const [name, setName] = useState('');
  const [error, setError] = useState('');
  function validate(value){
    if (!value) return 'Name is required';
    if (value.length < 3) return 'Name must be at least 3 characters';
    return '';
  }
  function onChange(e){
    const v = e.target.value;
    setName(v);
    setError(validate(v)); // live validation
  }
  function onSubmit(e){
    e.preventDefault();
    const err = validate(name);
    if (err) { setError(err); return; }
    alert(`Hello ${name}`);
  }
  return (
    <form onSubmit={onSubmit}>
      <label>Name: <input value={name} onChange={onChange} onBlur={() => setError(validate(name))} /></label>
      <button type="submit" style={{marginLeft:8}} disabled={!!error}>Submit</button>
      {error && <div style={{color:'salmon', marginTop:8}}>{error}</div>}
    </form>
  );
}
ReactDOM.createRoot(document.getElementById('try-inputs')).render(<NameForm />);
Syntax primer
- Controlled input: value=...withonChangeupdates state.
- onBlurfor validation when leaving the field;- onSubmitto validate on submit.
- e.preventDefault()prevents page reload on form submit.
Common pitfalls
- Mixing controlled and uncontrolled inputs; pick one pattern and stick to it.
- Forgetting to prevent default form submission (page reload).
Exercises
- Add an email field with a simple regex check and a combined form-level error summary.
- Disable the submit button only when there are errors or fields are empty.