Skip to content

Forms and Validation

The Course
•
20 min study

A form gathers several fields and submits them together. This one plans a study session. Try saving with an empty title, then with 2 minutes, then with valid values.

Plan a session React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState("25"); const [level, setLevel] = useState("easy"); const [error, setError] = useState(""); const [saved, setSaved] = useState(null); function handleSubmit(event) { event.preventDefault(); const amount = Number(minutes); if (title.trim() === "") { setError("Give the session a title."); return; } if (!Number.isInteger(amount) || amount < 5 || amount > 180) { setError("Minutes must be a whole number from 5 to 180."); return; } setError(""); setSaved({ title: title.trim(), minutes: amount, level }); setTitle(""); } return ( <main> <h1>Plan a session</h1> <form onSubmit={handleSubmit}> <label> Title{" "} <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} /> </label> <label> Minutes{" "} <input type="number" value={minutes} onChange={(e) => setMinutes(e.target.value)} /> </label> <label> Level{" "} <select value={level} onChange={(e) => setLevel(e.target.value)}> <option value="easy">Easy</option> <option value="medium">Medium</option> <option value="hard">Hard</option> </select> </label> {error && <p className="error">{error}</p>} <button type="submit">Save</button> </form> {saved && ( <p> Saved: {saved.title}, {saved.minutes} minutes, {saved.level}. </p> )} </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } label { display: block; margin: 0.5rem 0; } input, select, button { font: inherit; } input[type="text"], input[type="number"], select { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } .error { color: #b42318; margin: 0.25rem 0; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

onSubmit and preventDefault

The handler goes on the <form>, not on the button:

JSX
<form onSubmit={handleSubmit}>
  ...
  <button type="submit">Save</button>
</form>

That way pressing Enter in a field submits too, as users expect.

By default, a browser submits a form by loading a new page, which would throw away all your state. The first line of handleSubmit stops that:

JavaScript
event.preventDefault();

Delete that line, fill in a title and press Save. The Saved line never stays: the browser submits the form and starts the app again. Put the line back.

Every field's value is a string

Even <input type="number"> gives you a string in event.target.value. The minutes state stays a string while the user types, which allows a field that's briefly empty. It's turned into a number only when the form is submitted:

JavaScript
const amount = Number(minutes);

Number("") is 0, and Number("abc") is NaN. Number.isInteger rejects NaN and 2.5, but accepts 0. This form also requires amount >= 5 && amount <= 180, so 0 is rejected by the range check. Check both the converted number and the allowed range.

Selects and checkboxes

A <select> is controlled the same way as a text field: value={level} and onChange={(e) => setLevel(e.target.value)}. The <option> whose value matches is selected:

JSX
<select value={level} onChange={(e) => setLevel(e.target.value)}>
  <option value="easy">Easy</option>
  <option value="medium">Medium</option>
  <option value="hard">Hard</option>
</select>

A checkbox uses checked instead of value, and its new state is e.target.checked, which is true or false:

JSX
<input type="checkbox" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />

Validation

handleSubmit checks each rule in turn. The first failure sets an error message and returns before saving. Everything passing clears the error, saves, and empties the title for the next session:

JavaScript
function handleSubmit(event) {
  event.preventDefault();
  const amount = Number(minutes);
  if (title.trim() === "") {
    setError("Give the session a title.");
    return;
  }
  if (!Number.isInteger(amount) || amount < 5 || amount > 180) {
    setError("Minutes must be a whole number from 5 to 180.");
    return;
  }
  setError("");
  setSaved({ title: title.trim(), minutes: amount, level });
  setTitle("");
}

Errors are state too, so they appear and disappear through ordinary rendering: {error && <p className="error">{error}</p>}.

Showing every error at once

Stopping at the first failure is simple, but it's annoying to use. Leave both fields wrong and press Save: you're told about the title. Fix it, press Save again, and only now do you hear about the minutes.

To show every problem at once, check all the rules first and collect the messages in an object, one key per field. Then decide whether to save:

JavaScript
const errors = {};
if (title.trim() === "") {
  errors.title = "Give the session a title.";
}
if (!Number.isInteger(amount) || amount < 5 || amount > 180) {
  errors.minutes = "Minutes must be a whole number from 5 to 180.";
}
setErrors(errors);
if (Object.keys(errors).length > 0) {
  return;
}

Object.keys(errors) is an array of the object's key names, such as ["title", "minutes"], so a length of 0 means every rule passed. The state starts as an empty object, useState({}), and each field shows its own message underneath it:

JSX
{errors.title && <p className="error">{errors.title}</p>}

Use the first-failure version when one message is enough, and the collecting version when a form has several fields the user fills in together. The Day 5 checkpoint needs the second.

Your turn

Exercise

A reminder checkbox

Add a checkbox, Remind me, that starts unticked. Include it in the saved session, and show with a reminder at the end of the saved line when it was ticked.

Your working space React · 3 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; export default function App() { const [title, setTitle] = useState(""); const [minutes, setMinutes] = useState("25"); const [level, setLevel] = useState("easy"); const [error, setError] = useState(""); const [saved, setSaved] = useState(null); function handleSubmit(event) { event.preventDefault(); const amount = Number(minutes); if (title.trim() === "") { setError("Give the session a title."); return; } if (!Number.isInteger(amount) || amount < 5 || amount > 180) { setError("Minutes must be a whole number from 5 to 180."); return; } setError(""); setSaved({ title: title.trim(), minutes: amount, level }); setTitle(""); } return ( <main> <h1>Plan a session</h1> <form onSubmit={handleSubmit}> <label> Title{" "} <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} /> </label> <label> Minutes{" "} <input type="number" value={minutes} onChange={(e) => setMinutes(e.target.value)} /> </label> <label> Level{" "} <select value={level} onChange={(e) => setLevel(e.target.value)}> <option value="easy">Easy</option> <option value="medium">Medium</option> <option value="hard">Hard</option> </select> </label> {error && <p className="error">{error}</p>} <button type="submit">Save</button> </form> {saved && ( <p> Saved: {saved.title}, {saved.minutes} minutes, {saved.level}. </p> )} </main> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; } label { display: block; margin: 0.5rem 0; } input, select, button { font: inherit; } input[type="text"], input[type="number"], select { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } .error { color: #b42318; margin: 0.25rem 0; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

A checkbox is a controlled input like the others, but it is either on or off. So its state starts as a true/false value, and it reads and writes a different property from a text field. To show it after saving, the saved object has to remember it too.

Hint 2: a first step

Add the state and the checkbox first, using the pattern from Selects and checkboxes above. Tick and untick it: the box follows your clicks, so the state is wired up. Next, save a session and ask what setSaved receives. Is the checkbox's value in there?

Show one solution
JavaScript
const [remind, setRemind] = useState(false);
JSX
<label>
  <input type="checkbox" checked={remind} onChange={(e) => setRemind(e.target.checked)} />{" "}
  Remind me
</label>
JavaScript
setSaved({ title: title.trim(), minutes: amount, level, remind });
JSX
<p>
  Saved: {saved.title}, {saved.minutes} minutes, {saved.level}
  {saved.remind && ", with a reminder"}.
</p>

Was this article helpful?

Your response is saved on this device.