EthicsComputerCourses
Join training +91 90532 10052

Forms, Validation & Errors

MERN Stack · Lesson 12 of 20 Intermediate 11 min read Updated

By the end of this lesson TaskBoard will have a "New task" page at /tasks/new. Its form checks the obvious mistakes in the browser, sends the task to the API, shows the server's error messages next to the right fields, and cannot be submitted twice by an impatient double-click. You will also see why the browser checks are only a convenience, and the server checks are the real guard.

What you should know first: Routing with React Router for the pages and routes, and Error Handling & Middleware for the error shape { error: { message, details } } that this form reads. Form basics are taught in the React course: Forms & Controlled Inputs and Form Validation at Scale. Versions checked: React 19.3.1, react-router 8.5.1, and the Zod 4.6.7 schemas on the server. Every result below comes from a real Chrome session.

Two checkpoints, two jobs

Think of a passport application. The clerk at the Seva Kendra counter glances at your form: photo stuck on, every box filled. That saves you a wasted trip. But the passport office still checks everything again, against its own records, because a clerk can be careless and a form can be forged.

TaskBoard's form works the same way:

CheckWhereJobCan be skipped by
Title filled, at most 120 characters, date completeBrowser (taskRules.js)Fast, friendly feedbackAnyone with DevTools or curl
Same rules, plus "does this user exist?"Server (Zod and User.exists)Protects the databaseNobody

So the client rules mirror the server's rules, with the same limits, but they never replace them. Some checks can only happen on the server, because only the database knows the answer. "Is this assignee still a real user?" is one of them.

Step 1: Rules and a payload builder

Create client/src/utils/taskRules.js. It has no React in it, so it is easy to test later:

JavaScript
// Quick checks that mirror server/src/validation/tasks.validation.js.
// They save a round trip; the server still checks everything.
export const TITLE_MAX = 120;

export function validateTask(values) {
  const errors = {};
  const title = values.title.trim();
  if (!title) errors.title = "Title is required";
  else if (title.length > TITLE_MAX) errors.title = `Title must be ${TITLE_MAX} characters or fewer`;
  if (values.dueDate && !/^\d{4}-\d{2}-\d{2}$/.test(values.dueDate)) {
    errors.dueDate = "Enter a full date, for example 25/11/2026";
  }
  return errors;
}

// Form values are strings; the API wants null for "no date" and "nobody".
export function toTaskBody(values) {
  return {
    title: values.title.trim(),
    dueDate: values.dueDate || null,
    assignee: values.assignee || null,
  };
}

An <input type="date"> always gives its value as YYYY-MM-DD, whatever date format the user sees on screen. That is exactly the format the server's z.iso.date() accepts, so no conversion is needed. An empty date box gives "", which toTaskBody turns into null, the API's word for "no due date".

The "Assigned to" list needs the staff names. Add client/src/api/users.js:

JavaScript
import { apiRequest } from "./client.js";

export function getUsers({ signal } = {}) {
  return apiRequest("/api/users", { signal });
}

A small hooks/useUsers.js loads them once with the same AbortController pattern as useTasks, and returns an empty list if the request fails, so the form still works with "Unassigned".

Step 2: The TaskForm component

The form is a separate component, so the "edit task" page can reuse it. It takes the starting values, the staff list, a button label and an onSubmit function. Create client/src/components/TaskForm.jsx:

React JSX
import { useState } from "react";
import { TITLE_MAX, validateTask } from "../utils/taskRules.js";

const EMPTY = { title: "", dueDate: "", assignee: "" };

// Shows field messages from the client rules or from the server's error details.
export default function TaskForm({ initialValues = EMPTY, users, submitLabel, onSubmit }) {
  const [values, setValues] = useState(initialValues);
  const [errors, setErrors] = useState({});
  const [banner, setBanner] = useState("");
  const [submitting, setSubmitting] = useState(false);

  function change(event) {
    const { name, value } = event.target;
    setValues((v) => ({ ...v, [name]: value }));
    setErrors((e) => ({ ...e, [name]: undefined })); // the user is fixing it
    setBanner("");
  }

  async function handleSubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;
    setBanner("");
    const found = validateTask(values);
    if (Object.keys(found).length > 0) {
      setErrors(found);
      form.elements[Object.keys(found)[0]].focus();
      return;
    }
    setSubmitting(true);
    try {
      await onSubmit(values);
    } catch (err) {
      const fieldErrors = {};
      for (const d of err.details ?? []) if (d.field in EMPTY) fieldErrors[d.field] = d.message;
      setErrors(fieldErrors);
      const first = Object.keys(fieldErrors)[0];
      setBanner(first ? "Please fix the marked fields." : err.message);
      if (first) form.elements[first].focus();
    } finally {
      setSubmitting(false);
    }
  }

  const describe = (name) => (errors[name] ? `${name}-error` : undefined);
  // ... the JSX is shown below
}

Read handleSubmit from top to bottom; it is the whole story of a form:

  1. Client check. If validateTask finds problems, show them, move the keyboard focus to the first bad field, and stop. No request is sent.
  2. Lock the button. submitting disables the submit button while the request travels.
  3. Server check. onSubmit throws the ApiError from Fetching Data from Your API when the server says no. Its details array, such as [{ field: "assignee", message: "No user with this id" }], becomes field messages.
  4. Errors without a field, such as 401 "Please log in" or 403, go into the banner at the top.

The fields use the matching id, name and htmlFor, and point to their error message with aria-describedby, so a screen reader reads the message when the field gets focus:

React JSX
<form className="task-form" onSubmit={handleSubmit} noValidate>
  {banner && <p role="alert">{banner}</p>}

  <label htmlFor="title">Title</label>
  <input id="title" name="title" value={values.title} onChange={change} required maxLength={TITLE_MAX}
    aria-invalid={Boolean(errors.title)} aria-describedby={describe("title")} />
  {errors.title && <p id="title-error" className="field-error">{errors.title}</p>}

  <label htmlFor="dueDate">Due date (optional)</label>
  <input id="dueDate" name="dueDate" type="date" value={values.dueDate} onChange={change}
    aria-invalid={Boolean(errors.dueDate)} aria-describedby={describe("dueDate")} />
  {errors.dueDate && <p id="dueDate-error" className="field-error">{errors.dueDate}</p>}

  <label htmlFor="assignee">Assigned to</label>
  <select id="assignee" name="assignee" value={values.assignee} onChange={change}
    aria-invalid={Boolean(errors.assignee)} aria-describedby={describe("assignee")}>
    <option value="">Unassigned</option>
    {users.map((u) => (
      <option key={u.id} value={u.id}>{u.name}</option>
    ))}
  </select>
  {errors.assignee && <p id="assignee-error" className="field-error">{errors.assignee}</p>}

  <button type="submit" disabled={submitting}>{submitting ? "Saving..." : submitLabel}</button>
</form>

noValidate turns off the browser's own pop-up bubbles, so every message looks the same whether it came from the browser or the server. The required and maxLength attributes stay: required tells assistive technology the field is compulsory, and maxLength stops typing after 120 characters. In index.css, [aria-invalid="true"] gets a red border, so the styling follows the same attribute the screen reader uses.

Step 3: The New task page

Create client/src/pages/NewTaskPage.jsx. The page knows what to do with valid values; the form knows how to collect them:

React JSX
import { useNavigate } from "react-router";
import TaskForm from "../components/TaskForm.jsx";
import { createTask } from "../api/tasks.js";
import { useUsers } from "../hooks/useUsers.js";
import { toTaskBody } from "../utils/taskRules.js";

export default function NewTaskPage() {
  const navigate = useNavigate();
  const users = useUsers();

  async function save(values) {
    const task = await createTask(toTaskBody(values)); // throws ApiError on 400, 401...
    navigate(`/tasks/${task.id}`);
  }

  return (
    <section>
      <h2>New task</h2>
      <TaskForm users={users} submitLabel="Create task" onSubmit={save} />
    </section>
  );
}

In App.jsx, add <Route path="tasks/new" element={<NewTaskPage />} />. As the routing lesson showed, the fixed segment new wins over :id, so the order of the two lines does not matter. Add <NavLink to="/tasks/new">New task</NavLink> to the header. useNavigate() returns a function that changes the page from code; after a successful save, the teacher lands on the new task's page.

Step 4: Try every path

Signed in as Priya, we tried the form in Chrome. Pressing "Create task" on the empty form:

Output
Title is required
(focus moved to the Title box, which got aria-invalid="true"; the Network tab showed no request)

Next, a check only the server can make. As Kabir, we added a teacher, Rohan Verma. Priya opened the form, so Rohan was in her list. While her form was still open, we removed Rohan's account from the database, as if an admin had deleted it. Priya then chose Rohan and submitted. The browser rules passed, but the API replied 400, and the form showed:

Output
Please fix the marked fields.
Assigned to: [Rohan Verma]  No user with this id
(focus moved to the Assigned to list)

That message came from assertAssigneeExists in the tasks controller, through ApiError.details, to the right field, with no special code for this case. Choosing Priya instead and submitting again gave 201 Created, and the app moved to the new task's page:

Output
/tasks/6afac8197af9c977687d7271
Book hall for parent meeting
Status To do · Due 25 Nov · Assigned to Priya Sharma

Two more checks. A real mouse double-click on "Create task" sent one POST, because the first click disabled the button before the second arrived. And after we signed Priya out from the console, submitting showed the banner "Please log in", the server's 401 message. In Login, Protected Routes & Sessions that case will take her to the login page instead.

See the form in action

This version runs on its own. The fake save replies like the real API: it rejects "Rohan Verma" with the same 400 body, and otherwise succeeds after a short delay.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const USERS = [{ id: "u1", name: "Priya Sharma" }, { id: "u2", name: "Kabir Malik" }, { id: "u9", name: "Rohan Verma" }];
const EMPTY = { title: "", dueDate: "", assignee: "" };

function validateTask(values) {
  const errors = {};
  const title = values.title.trim();
  if (!title) errors.title = "Title is required";
  else if (title.length > 120) errors.title = "Title must be 120 characters or fewer";
  return errors;
}

// Fake API: Rohan's account was deleted, so the server refuses him.
function fakeSave(body) {
  return new Promise((resolve, reject) => setTimeout(() => {
    if (body.assignee === "u9") {
      const err = new Error("Validation failed");
      err.details = [{ field: "assignee", message: "No user with this id" }];
      reject(err);
    } else resolve({ id: "t42", ...body });
  }, 800));
}

function TaskForm() {
  const [values, setValues] = useState(EMPTY);
  const [errors, setErrors] = useState({});
  const [banner, setBanner] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const change = (e) => {
    setValues((v) => ({ ...v, [e.target.name]: e.target.value }));
    setErrors((x) => ({ ...x, [e.target.name]: undefined }));
    setBanner("");
  };

  async function submit(e) {
    e.preventDefault();
    const form = e.currentTarget;
    const found = validateTask(values);
    if (Object.keys(found).length) { setErrors(found); form.elements[Object.keys(found)[0]].focus(); return; }
    setSubmitting(true);
    try {
      const task = await fakeSave({ title: values.title.trim(), dueDate: values.dueDate || null, assignee: values.assignee || null });
      setValues(EMPTY);
      setBanner(`Created "${task.title}"`);
    } catch (err) {
      const fieldErrors = Object.fromEntries((err.details ?? []).map((d) => [d.field, d.message]));
      setErrors(fieldErrors);
      setBanner(Object.keys(fieldErrors).length ? "Please fix the marked fields." : err.message);
      if (fieldErrors.assignee) form.elements.assignee.focus();
    } finally {
      setSubmitting(false);
    }
  }

  const red = (name) => (errors[name] ? { border: "2px solid crimson" } : {});
  return (
    <form onSubmit={submit} noValidate style={{ display: "grid", gap: 6, maxWidth: 320 }}>
      {banner && <p role="alert"><strong>{banner}</strong></p>}
      <label htmlFor="title">Title</label>
      <input id="title" name="title" value={values.title} onChange={change} maxLength={120} style={red("title")} aria-invalid={Boolean(errors.title)} />
      {errors.title && <span style={{ color: "crimson" }}>{errors.title}</span>}
      <label htmlFor="dueDate">Due date (optional)</label>
      <input id="dueDate" name="dueDate" type="date" value={values.dueDate} onChange={change} />
      <label htmlFor="assignee">Assigned to</label>
      <select id="assignee" name="assignee" value={values.assignee} onChange={change} style={red("assignee")} aria-invalid={Boolean(errors.assignee)}>
        <option value="">Unassigned</option>
        {USERS.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
      </select>
      {errors.assignee && <span style={{ color: "crimson" }}>{errors.assignee}</span>}
      <button disabled={submitting}>{submitting ? "Saving..." : "Create task"}</button>
    </form>
  );
}

createRoot(document.getElementById("root")).render(<TaskForm />);

Press "Create task" with an empty title: "Title is required" appears at once. Type a title, choose Rohan Verma and submit: after "Saving..." the list turns red with "No user with this id". Choose Priya and submit: the banner says Created "..." and the form clears.

Why the button is disabled

The demo below fakes a slow network. Untick "disable while saving" and click the button three times quickly: three tasks are "created". With the box ticked, only one is.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

function DoubleSubmit() {
  const [guard, setGuard] = useState(true);
  const [saving, setSaving] = useState(false);
  const [created, setCreated] = useState(0);

  async function save() {
    setSaving(true);
    await new Promise((r) => setTimeout(r, 1500)); // a slow 4G connection
    setCreated((n) => n + 1);
    setSaving(false);
  }

  return (
    <div>
      <label><input type="checkbox" checked={guard} onChange={(e) => setGuard(e.target.checked)} /> disable while saving</label>
      <p><button onClick={save} disabled={guard && saving}>{saving ? "Saving..." : "Create task"}</button></p>
      <p>Tasks created: <strong>{created}</strong></p>
      <button onClick={() => setCreated(0)}>Reset</button>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<DoubleSubmit />);

Disabling the button protects honest users. It cannot stop a script that posts twice, so the server must cope with duplicates on its own. For payments, servers often accept an idempotency key, a random id sent with the request, so a repeated request is recognised and done only once.

Common mistakes

  • Trusting client validation. It is skipped by DevTools, curl or a bug. The server must check every field again.
  • Setting Content-Type and JSON.stringify in each form. Let apiRequest do it once.
  • Showing only "Validation failed". The details array names each field; put each message next to its input.
  • Different limits on each side. A client that allows 200 characters while the server allows 120 gives confusing errors. Keep the numbers the same.
  • Sending "" for empty optional fields. The API expects null for "no date" and "nobody"; convert in one place.
  • Error text in colour only. Use visible text, aria-invalid and aria-describedby, and move focus to the first problem.

Interview questions

1. If the server validates everything, why validate in the browser too?

For speed and kindness: the user gets feedback at once, without a network round trip, and the server gets fewer bad requests. It is not security, because anyone can bypass the browser. The server's validation is the one that protects the data.

2. How do you show server validation errors in a React form?

Agree on an error shape with the API, such as { error: { message, details: [{ field, message }] } }. The fetch layer throws an error object carrying details; the form maps each detail to its field's message and shows message in a banner when no field matches.

3. How do you stop a form being submitted twice?

Disable the submit button while the request is in flight, and ignore submits while a flag is set. On the server, design operations to tolerate repeats, for example with unique constraints or idempotency keys, because a client-side guard can always be bypassed.

4. What makes a form error accessible?

The message is visible text placed next to its field, linked with aria-describedby, and the field is marked aria-invalid="true". Focus moves to the first invalid field, and a summary uses role="alert" so screen readers announce it.

Key points

  • Client checks in taskRules.js mirror the server's Zod limits for fast feedback; the server stays the real guard.
  • TaskForm collects values with controlled inputs and calls onSubmit; pages decide what saving means.
  • ApiError.details become field messages; errors without a field go in a role="alert" banner.
  • toTaskBody turns empty strings into null and trims the title, in one place.
  • Disable the button while saving, and design the server to cope with repeated requests anyway.
  • Use labels, aria-invalid, aria-describedby and focus on the first error, so everyone can fix mistakes.

Exercise

Add an "Edit task" page at /tasks/:id/edit that reuses TaskForm. Load the task with useTask(id), fill the form from it (the date box needs YYYY-MM-DD, the list needs the assignee's id), and save with updateTask. Then add an "Edit task" link on the task page. Test it as Priya on her own task, and on Kabir's task, where the server answers 403.

Show solution
React JSX
// pages/EditTaskPage.jsx
import { useNavigate, useParams } from "react-router";
import TaskForm from "../components/TaskForm.jsx";
import { updateTask } from "../api/tasks.js";
import { useTask } from "../hooks/useTask.js";
import { useUsers } from "../hooks/useUsers.js";
import { toTaskBody } from "../utils/taskRules.js";
import NotFoundPage from "./NotFoundPage.jsx";

export default function EditTaskPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { task, loading, error } = useTask(id);
  const users = useUsers();

  if (loading) return <p>Loading task...</p>;
  if (error?.status === 404) return <NotFoundPage title="Task not found" />;
  if (error) return <p role="alert">Could not load the task: {error.message}</p>;

  const initialValues = {
    title: task.title,
    dueDate: task.dueDate?.slice(0, 10) ?? "",
    assignee: task.assignee?.id ?? "",
  };

  async function save(values) {
    await updateTask(id, toTaskBody(values));
    navigate(`/tasks/${id}`);
  }

  return (
    <section>
      <h2>Edit task</h2>
      <TaskForm initialValues={initialValues} users={users} submitLabel="Save changes" onSubmit={save} />
    </section>
  );
}

// App.jsx: <Route path="tasks/:id/edit" element={<EditTaskPage />} />
// TaskPage.jsx: <Link to={`/tasks/${task.id}/edit`}>Edit task</Link>
Output
Priya, her worksheets task: the form opened with "Print Class 10 maths worksheets / 2026-11-20 / Priya Sharma".
  Changed the date to 21 Nov, saved: PATCH 200, back on the task page.
Priya, Kabir's task: changed the title, saved: PATCH 403, banner "You can only change tasks assigned to you".

TaskForm reads initialValues only once, when it mounts. That is fine here, because the page renders the form only after the task has loaded. The 403 needed no new code: it has no details, so its message went to the banner.

Quick Quiz

1. Why does TaskBoard keep validating on the server when the form already checks the title?

2. The API replies 400 with details: [{ field: "assignee", message: "No user with this id" }]. What does TaskForm do?

3. What does an empty <input type="date"> give, and what does TaskBoard send?

4. What is the main purpose of disabled={submitting} on the button?

Learn MERN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call