Advanced Forms — React

Validation is checking what's in a form before it's accepted. Checking on submit: in onSubmit, call e.preventDefault() so the page doesn't reload, check the…

You sign up for an account, press Send, and a red line appears at the very top: "Something is wrong". Which part? You have to search for it yourself, field by field.

A good form checks what was typed before it accepts it. Then the form says what's not right, directly at the field that's wrong. That checking is called validation. Validation is like a registration clerk at a counter. You hand the form to the clerk, and the clerk checks it. If the name is empty, the clerk points at that field and says "Name is required". If everything is fine, the clerk stamps the form "Accepted". Some clerks check the form when you give it to them, and others read it while you write. In React, the clerk is your code, and your code can check in the same two ways: when the form is submitted, or as the person types. You write both yourself with state.

Check on submit

This form has one name field, and checks it when the form is submitted:

function App() {
  const [name, setName] = useState("")
  const [error, setError] = useState("")
  const [success, setSuccess] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault()
    if (!name.trim()) {
      setError("Name is required")
      setSuccess(false)
    } else {
      setError("")
      setSuccess(true)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input id="name" value={name} onChange={(e) => setName(e.target.value)} />
      {error && <span id="error">{error}</span>}
      {success && <span id="success">Success!</span>}
      <button type="submit">Submit</button>
    </form>
  )
}

Before you look at the table, take a guess. You submit the name Budi, and Success! appears. Then you delete the name without pressing Submit. Is Success! still shown or gone?

This is what happens to the Name field in the Lab, step by step:

Step name error success Shown
Submit with the field empty "" "Name is required" false Name is required
Type Budi "Budi" "Name is required" false Name is required
Submit "Budi" "" true Success!
Delete the name "" "" true Success!
Submit again "" "Name is required" false Name is required

Typing only changes name. error and success only change when the form is submitted. So after the name is deleted, Success! is still there, because that message is the result of the last submit.

Check as you type

Sometimes people need to know what's wrong while they type, for example for the rules of a password. The way to do it: don't keep the message in state. Calculate the message directly from the input, during the render. Every keystroke calls a setter, React renders again, then the rule is checked again. This form checks the email and the password every time you type:

function App() {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")

  return (
    <form>
      <input id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      {!email.includes("@") && <span id="email-error">Email must contain @</span>}

      <input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      {password.length < 6 && <span id="password-error">Password must be at least 6 characters</span>}
    </form>
  )
}

Type [email protected]: as soon as you type @, the email message disappears. Type mysecret123: at the sixth letter, the password message disappears. The downside of this way: the red messages are there before anyone has typed anything. A common middle way: show a field's message once the person leaves that field (moves to another field), with the onBlur event. In the Lab, you can try all three ways: on submit, as you type, and when a field is left.

Many fields, one handler

A form with many fields only needs one state object for every field, and one handler for all of them.

function SignupForm() {
  const [form, setForm] = useState({ name: "", email: "", password: "" })

  function handleChange(e) {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }))
  }

  return (
    <form>
      <input name="name" value={form.name} onChange={handleChange} />
      <input name="email" value={form.email} onChange={handleChange} />
      <input name="password" type="password" value={form.password} onChange={handleChange} />
    </form>
  )
}

Controlled or uncontrolled

All the examples above are controlled components: what's in the field is kept in React state, through value and onChange. The opposite is an uncontrolled component: the value is kept in the DOM, and you only read it when you need it, through a ref. This search form uses a ref:

function SearchForm() {
  const cityRef = useRef(null)

  function handleSubmit(e) {
    e.preventDefault()
    console.log("Search:", cityRef.current.value)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input ref={cityRef} defaultValue="Manchester" />
      <button type="submit">Search</button>
    </form>
  )
}
Controlled Uncontrolled
The value is kept in React state the DOM
Read through the state variable a ref, when needed
Checking as you type possible not possible
Good for almost every form simple forms with no checking as you type, or a non-React library that manages its own inputs

📌 When the form keeps growing

A form with 10 fields and lots of rules quickly becomes hundreds of lines of useState and if. In real apps, people usually use React Hook Form together with Zod. React Hook Form handles the values, the errors and the submit status. With Zod, the validation rules are written once, as a schema (a list of rules for each field). The basics stay what you learned here: check, keep the result, then show the message next to its field.

Other options for checking a form:

Way When to pick it
HTML attributes: required, type="email", minLength A simple form: the browser stops the submit and shows the message.
State and if Your own messages. This lesson uses this way because you can see every step.
<form action> with useActionState (React 19) A form that is sent to a server.
React Hook Form with Zod A big form with many fields and rules.

Here is an example of useActionState. You import this hook from "react", the same as useState:

async function signUp(oldMessage, formData) {
  const name = formData.get("name")
  if (!name.trim()) return "Name is required"
  return `Done, ${name}!`
}

function SignUpForm() {
  const [message, send, isPending] = useActionState(signUp, "")
  return (
    <form action={send}>
      <input name="name" />
      <button type="submit" disabled={isPending}>Send</button>
      {message && <p>{message}</p>}
    </form>
  )
}

⚠️ Validation messages that appear wrongly, or never get the chance to appear

TL;DR: Validation is checking what's in a form before it's accepted. Checking on submit: in onSubmit, call e.preventDefault() so the page doesn't reload, check the input, then keep the result in state (error, success). Set both in every if branch. That result stays until the next submit, because typing doesn't change it. Checking as you type: calculate the rule during the render (!email.includes("@"), password.length < 6), then show the message with condition && <span>. The message is gone from the page once the input is valid. onBlur (when a field is left) is the middle way. Many fields need just one handler: [e.target.name] uses the input's name attribute as the property name. A controlled component keeps what's in the field in state. An uncontrolled one keeps it in the DOM and reads it through a ref, which suits simple forms with no checking as you type. The server still has to check again.

⚡ Check on submit

Write:

const handleSubmit = (e) => {
  e.preventDefault()
  if (!name.trim()) {
    setError("Name is required")
    setSuccess(false)
  } else {
    setError("")
    setSuccess(true)
  }
}
Guess first: you submit the name Budi, so success is true and Success! appears. Then you delete the name without pressing Submit. Is Success! still there, or gone?

Still there. Typing only changes name, while error and success only change when the form is submitted.

Meaning: handleSubmit is set on the form's onSubmit, so it runs when the form is submitted. e.preventDefault() stops the page from reloading. name is the state that holds what's in the name field. If name is empty, error gets a message. If it isn't empty, success becomes true. Set both in every branch: if the failing branch forgets setSuccess(false), the old success message stays next to the error.

⚡ Check while typing

Write:

{!email.includes("@") && <span id="email-error">Email must contain @</span>}

Meaning: email is state that changes every time you type. The condition !email.includes("@") is calculated again on every render, so the message disappears as soon as the input contains @. The downside: the red message is there before anyone has typed.

⚡ Uncontrolled: the browser holds it

Write:

<input ref={cityRef} defaultValue="Manchester" />

Meaning: defaultValue only fills in the starting value. After that, the value is kept in the DOM, not in state. cityRef is a ref, so the value is read through cityRef.current.value when it's needed. It suits a simple form with no checking as you type. For checking while typing, use a controlled component (the value is in state, through value and onChange).

What you will learn