ProgramGuru

Forms and Validation in React

Forms and Validation in React — purpose and prerequisites

React form state is not automatically validated by TypeScript. Use controlled input values, keep errors separately, and validate when submitting or when appropriate during typing. The same validation function can be tested outside React; the TSX component then shows its errors next to the fields.

What you’ll learn

  • Explain the purpose of forms and validation in react.
  • Identify the typed contract, runtime responsibilities and common pitfalls.
  • Run the example and extend its behavior with a practical exercise.

How the idea works

The validator converts age and checks basic field rules. A real signup service needs stronger email confirmation and server-side validation; a React UI check is only the first layer.

Client-side validation improves feedback but users can bypass it, so servers must validate received data again.

Visualize the flow

Forms and Validation in React — learning flowControlled fields → Validate at submit → Show feedbackForms and Validation in React1Controlled fields2Validate at submit3Show feedbackStatic contracts need runtime checks at external boundaries.
A three-step view of the responsibilities and the observable result.

Run the checked TypeScript example

This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.

TypeScript source

type Signup = { email: string; age: number };
function validate(email: string, ageText: string): Signup | null {
  const age = Number(ageText);
  if (!email.includes("@") || !Number.isInteger(age) || age < 13) return null;
  return { email: email.trim(), age };
}
console.log(validate("maya@example.test", "16"));
console.log(validate("invalid", "16"));

Verified output

{ email: 'maya@example.test', age: 16 }
null

Compile: npx tsc --strict --target es2022 --module commonjs forms-validation-react.ts; run: node forms-validation-react.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.

Trace the execution

The validator converts age and checks basic field rules. A real signup service needs stronger email confirmation and server-side validation; a React UI check is only the first layer.

Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.

Build the practical integration

Integration companion: The primary example above is self-contained. The files below demonstrate a real framework, runtime, or project setup and may need additional packages or a browser.

src/Tasks.tsx

import { useState, type FormEvent } from "react";
type Todo = Readonly<{ id: number; title: string; done: boolean }>;
export default function Tasks() {
  const [tasks, setTasks] = useState<Todo[]>([]);
  const [title, setTitle] = useState("");
  function add(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!title.trim()) return;
    setTasks(current => [...current, { id: Date.now(), title: title.trim(), done: false }]);
    setTitle("");
  }
  return <section><h1>Tasks</h1><form onSubmit={add}>
    <input aria-label="Task title" value={title} onChange={e => setTitle(e.currentTarget.value)} />
    <button>Add</button></form>
    <ul>{tasks.map(task => <li key={task.id}><label>
      <input type="checkbox" checked={task.done} onChange={() => setTasks(current =>
        current.map(item => item.id === task.id ? { ...item, done: !item.done } : item))} />
      {task.title}</label></li>)}</ul>
  </section>;
}

Setup and execution

npm create vite@latest typed-tasks -- --template react-ts
cd typed-tasks
Edit src/App.tsx with the component shown above
npm install
npm run dev
npm run build

This is a real React TSX component, not a Node-only simulation. Use the React+TypeScript Vite template, and place the component in the application's src/App.tsx. Its imports require React packages and @types/react; browser behavior was not executed in this environment.

Validation: This companion requires the named external packages or browser environment. Its runtime behavior was not executed during the course build.

Common mistake and correction

Client-side validation improves feedback but users can bypass it, so servers must validate received data again.

Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.

Your turn: extend the example

Write a form that calls validate in onSubmit, prevents default submission, and displays a precise error.

Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.

Check your understanding

Which statement correctly describes forms and validation in react in the example?
Choose one answer. You can try again.

Answer and explanation

The validator converts age and checks basic field rules.

The validator converts age and checks basic field rules. A real signup service needs stronger email confirmation and server-side validation; a React UI check is only the first layer.

Additional official reference

Review the official documentation for the provider, framework or runtime, especially when installing a newer major version.

Key idea to remember

The validator converts age and checks basic field rules. A real signup service needs stronger email confirmation and server-side validation; a React UI check is only the first layer.

Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Database Integration with TypeScript →