EthicsComputerCourses
Join training +91 90532 10052

Reactive Forms & Validation

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

By the end of this lesson librarians will have one form for adding a book and editing it. The form checks the same rules as the server while the librarian types, sends the data with BooksApi, and when the API still says no, places each server message under the right input: "Already in use" under ISBN, "4 copies are on loan" under Copies, "Please log in" above the form.

What you should know first: Routing & Route Guards, whose routes and validIdGuard you will extend, and CRUD Endpoints & Validation, which defined the Zod rules and the error shape. The form APIs are taught in Reactive Forms and Signal Forms in the Angular course. Versions used: Angular 22.2.6 (CLI 22.2.7), Zod 4.6.7 on the server, Express 5.3.0 and Node.js 26.13.1. All output is from real runs.

Which forms API: reactive forms or Signal Forms?

Angular has two model-driven ways to build forms. Reactive forms describe each input with a FormControl object inside a FormGroup; they have been the standard for years and are fully typed. Signal Forms keep the form's data in an ordinary signal and build the form on top of it. Signal Forms were experimental in Angular 21. We checked the Angular 22.2.6 package: every public Signal Forms API in @angular/forms/signals (form, FormField, FormRoot, submit, the validators) is marked @publicApi 22.0, which means stable. Only an optional WebMCP helper is still experimental.

LibTrack is built on signals already, so this lesson uses Signal Forms. A short section at the end shows the same form with typed FormGroup, because most existing projects you join will use it. Both are "reactive" in the everyday sense: the form reacts to every keystroke without a page reload.

The integration problem is the same either way. Think of the railway reservation counter. The clerk checks your form for blanks and a 10-digit mobile number before typing anything (client rules). Then the computer says "no berth left in S4" (a server rule). A good clerk writes that reason next to the right box on your form, instead of just saying "rejected".

RuleChecked in AngularChecked by the API
Title and author required, max lengthyes, while typingyes, Zod
ISBN has exactly 13 digitsyesyes, Zod
Copies is a whole number from 1 to 50yesyes, Zod
Title is not only spacesnoyes, Zod .trim()
ISBN not used by another bookno, needs the databaseyes, unique index, 409
Copies not below the number on loanno, needs the loansyes, 409 COPIES_ON_LOAN
Logged in as a librariannoyes, 401 or 403

The client copies the cheap rules for speed. The server keeps every rule, because anyone can skip the form.

Step 1: generate the form and add its routes

Terminal
ng generate component books/book-form
Output
CREATE src/app/books/book-form/book-form.spec.ts (569 bytes)
CREATE src/app/books/book-form/book-form.ts (206 bytes)
CREATE src/app/books/book-form/book-form.css (0 bytes)
CREATE src/app/books/book-form/book-form.html (25 bytes)

One component serves two URLs. Add these routes to app.routes.ts, before books/:id, or the router would read new as an id:

TypeScript
{
  path: 'books/new',
  title: 'Add a book | LibTrack',
  loadComponent: () => import('./books/book-form/book-form').then((m) => m.BookForm),
},
{
  path: 'books/:id/edit',
  title: 'Edit book | LibTrack',
  canActivate: [validIdGuard],
  loadComponent: () => import('./books/book-form/book-form').then((m) => m.BookForm),
},

Add an "Add book" link to the header in app.html and an "Edit" link on the detail page: <a [routerLink]="['/books', id(), 'edit']">Edit</a>.

Step 2: one helper for server errors

The API's error body has a details list of { field, message }, as fixed in the project structure lesson. Signal Forms accept errors from a submit action as objects with a kind, a message and a fieldTree: the field the error belongs to. Create client/src/app/core/form-errors.ts to translate one into the other:

TypeScript
import { HttpErrorResponse } from '@angular/common/http';
import { isFieldTree, type FieldTree, type ValidationError } from '@angular/forms/signals';
import { apiErrorMessage } from './api-error';
import type { ApiErrorBody } from '../../../../shared/api-types';

// Turns an API error into Signal Forms errors, one under each field the server named.
// fieldForCode maps error codes that name no field (such as COPIES_ON_LOAN) to an input.
// Returns an empty list when no field fits; the caller then shows a general message.
export function serverErrors<T>(
  err: unknown,
  fields: FieldTree<T>,
  fieldForCode: Record<string, string> = {},
): ValidationError.WithOptionalFieldTree[] {
  const body = err instanceof HttpErrorResponse ? (err.error as Partial<ApiErrorBody> | null) : null;
  const byName = fields as unknown as Record<string, unknown>;
  const errors: ValidationError.WithOptionalFieldTree[] = [];

  for (const detail of body?.error?.details ?? []) {
    const field = byName[detail.field];
    if (isFieldTree(field)) errors.push({ kind: 'server', message: detail.message, fieldTree: field });
  }
  const codeField = byName[fieldForCode[body?.error?.code ?? ''] ?? ''];
  if (errors.length === 0 && isFieldTree(codeField)) {
    errors.push({ kind: 'server', message: apiErrorMessage(err), fieldTree: codeField });
  }
  return errors;
}

Field names come from the server, so the helper never trusts them blindly: isFieldTree() confirms that the name really is a field of this form before using it. A detail for a field the form does not have is simply skipped. Because this works with any form, the login page in the next lesson reuses the same idea.

Step 3: the BookForm component

Replace books/book-form/book-form.ts:

TypeScript
import { Component, OnInit, inject, input, signal } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { FormField, FormRoot, form, max, maxLength, min, pattern, required, validate } from '@angular/forms/signals';
import { firstValueFrom } from 'rxjs';
import { BooksApi } from '../books-api';
import { apiErrorMessage } from '../../core/api-error';
import { serverErrors } from '../../core/form-errors';
import type { BookInput, Category } from '../../../../../shared/api-types';

@Component({
  imports: [FormField, FormRoot, RouterLink],
  selector: 'app-book-form',
  styleUrl: './book-form.css',
  templateUrl: './book-form.html',
})
export class BookForm implements OnInit {
  private readonly api = inject(BooksApi);
  private readonly router = inject(Router);

  // From the URL: set on /books/:id/edit, undefined on /books/new.
  readonly id = input<string>();

  protected readonly categories: Category[] = ['Computer Science', 'Commerce', 'Literature', 'Science'];

  // Problems that belong to no single field, such as "Please log in".
  protected readonly saveError = signal('');

  // The model: a plain signal shaped exactly like the API's BookInput.
  protected readonly model = signal<BookInput>({
    title: '', author: '', isbn: '', category: 'Literature', copies: 1,
  });

  protected readonly bookForm = form(
    this.model,
    (book) => {
      required(book.title, { message: 'Title is required' });
      maxLength(book.title, 200, { message: 'Title can have at most 200 characters' });
      required(book.author, { message: 'Author is required' });
      maxLength(book.author, 120, { message: 'Author can have at most 120 characters' });
      required(book.isbn, { message: 'ISBN is required' });
      pattern(book.isbn, /^\d{13}$/, { message: 'ISBN must have exactly 13 digits' });
      min(book.copies, 1, { message: 'At least 1 copy' });
      max(book.copies, 50, { message: 'At most 50 copies' });
      validate(book.copies, ({ value }) =>
        Number.isInteger(value()) ? null : { kind: 'wholeNumber', message: 'Copies must be a whole number' });
    },
    {
      submission: {
        action: async (fields) => {
          const id = this.id();
          this.saveError.set('');
          try {
            const saved = await firstValueFrom(
              id ? this.api.update(id, this.model()) : this.api.create(this.model()),
            );
            await this.router.navigate(['/books', saved.id]);
            return null;
          } catch (err) {
            const fieldErrors = serverErrors(err, fields, { COPIES_ON_LOAN: 'copies' });
            if (fieldErrors.length === 0) this.saveError.set(apiErrorMessage(err));
            return fieldErrors;
          }
        },
      },
    },
  );

  ngOnInit() {
    const id = this.id();
    if (!id) return;
    this.api.get(id).subscribe(({ title, author, isbn, category, copies }) =>
      this.model.set({ title, author, isbn, category, copies }));
  }
}

What each part does:

  • The model is typed with the shared BookInput. If the API adds a required field to the contract, this line stops compiling until the form has it too. form() turns the model into a field tree: bookForm.isbn is the ISBN field, and calling it, bookForm.isbn(), gives its state signals such as errors() and touched().
  • The schema function mirrors the Zod schema from the CRUD lesson, with the same messages, so a librarian sees the same words from either side.
  • The submit action runs only when the client rules pass. firstValueFrom() turns the Observable from BooksApi into a promise the action can await. Returning null means success; returning a list of errors attaches them to fields.
  • saveError is a separate signal. We first returned general errors (such as 401) as form-level errors too. In the test run, that error kept the whole form invalid, so the next click on Save did nothing until the librarian changed a field. A general problem is not caused by a value, so it now lives in its own signal.
  • Edit mode reads the id input in ngOnInit, because inputs are not set in the constructor, and copies only the five editable fields into the model.

Step 4: the template

Each input is bound with [formField], and the <form> with [formRoot]. FormRoot sets novalidate, stops the page reload, marks every field as touched and calls the submit action:

HTML
<h2>{{ id() ? 'Edit book' : 'Add a book' }}</h2>

<form [formRoot]="bookForm">
  @if (saveError()) {
    <p class="error" role="alert">{{ saveError() }}</p>
  }

  <label for="isbn">ISBN (13 digits)</label>
  <input id="isbn" inputmode="numeric" [formField]="bookForm.isbn" />
  @if (bookForm.isbn().touched()) {
    @for (error of bookForm.isbn().errors(); track error.kind) {
      <p class="field-error">{{ error.message }}</p>
    }
  }

  <label for="copies">Copies</label>
  <input id="copies" type="number" [formField]="bookForm.copies" />
  <!-- title, author and copies errors follow the same pattern as isbn -->

  <label for="category">Category</label>
  <select id="category" [formField]="bookForm.category">
    @for (c of categories; track c) {
      <option [value]="c">{{ c }}</option>
    }
  </select>

  <button type="submit" [disabled]="bookForm().submitting()">
    {{ bookForm().submitting() ? 'Saving...' : 'Save book' }}
  </button>
</form>

Only part of the template is shown; the title and author blocks match the ISBN block. type="number" makes [formField] write a real number into copies, not a string, so the request body matches BookInput. Showing errors only after touched() stops the form from shouting at a librarian who has not typed yet.

Step 5: try every kind of error

With the API and ng serve running, we drove /books/new in headless Chrome and printed each input's error after every step (the output is shortened). Until the login page exists in the next lesson, we logged in as Meera by calling POST /api/auth/login with fetch(..., { credentials: 'include' }) from the browser console.

Output
== Save with an empty form ==
title: Title is required | author: Author is required | isbn: ISBN is required
== after typing bad values ==
isbn: ISBN must have exactly 13 digits | copies: Copies must be a whole number
values: ["   ","Munshi Premchand","97893","Literature","2.5"]
model: {"title":"   ","author":"Munshi Premchand","isbn":"97893","category":"Literature","copies":2.5}
== submit, not logged in ==
form: Please log in
== submit as Meera, title is only spaces ==
title: Title is required
== after typing a real title ==
(no errors)
== submit with Godan's ISBN ==
isbn: Already in use
== after changing the ISBN ==
(no errors)
== saved ==
URL: /books/6afb08ef648a6cdddc0c3da5
Gaban
Author
Munshi Premchand

Then we opened Godan's edit page after marking four of its copies as borrowed, and changed copies to 2:

Output
edit values: ["Godan","Premchand","9789300000011","Literature","4"]
== Godan: copies 2 while 4 are on loan ==
copies: 4 copies are on loan, so copies cannot be less than 4

Meanwhile the API's request log showed which attempts reached the server (the GET lines are left out):

Output
POST /api/books 401 2ms
POST /api/auth/login 200 3127ms
POST /api/books 400 4ms
OPTIONS /api/books 204 2ms
POST /api/books 409 8ms
POST /api/books 201 7ms
PATCH /api/books/6afb08d13a13d308fb26d02a 409 8ms

Read the two outputs together. The empty form and the bad values never reached the API: the client rules blocked them, and the model already held the number 2.5, not the text "2.5". The title made only of spaces passed the client's required rule, but Zod trimmed it and answered 400; the helper put "Title is required" under Title. The duplicate ISBN came back as 409 with details, and "Already in use" appeared under ISBN. COPIES_ON_LOAN names no field, so the fieldForCode map placed it under Copies. Each server error disappeared as soon as the librarian edited that field. The OPTIONS line is the browser's CORS preflight: a permission check it sends before a cross-origin JSON POST.

Practise: client rules, then server rules

This page imitates the same two layers in plain JavaScript. A fake server knows that Godan's ISBN is taken. Press Save as it is, then fix the ISBN format, then change the ISBN again, and watch which layer answers each time.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Two layers of validation</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-width: 420px; }
    label { display: block; margin-top: 8px; font-weight: 600; }
    input { width: 100%; font-size: 1rem; padding: 4px; }
    .err { color: #b00020; margin: 2px 0; min-height: 1.2em; }
  </style>
</head>
<body>
  <h1>Add a book</h1>
  <form id="f" novalidate>
    <label for="title">Title</label><input id="title" value="Gaban">
    <p class="err" id="title-err"></p>
    <label for="isbn">ISBN</label><input id="isbn" value="97893">
    <p class="err" id="isbn-err"></p>
    <button>Save</button>
  </form>
  <p id="log"></p>

  <script>
    const taken = ["9789300000011"];
    const clientRules = {
      title: (v) => (v === "" ? "Title is required" : ""),
      isbn: (v) => (/^\d{13}$/.test(v) ? "" : "ISBN must have exactly 13 digits"),
    };

    // Pretends to be the API: answers like LibTrack's 409 DUPLICATE.
    async function fakeApi(book) {
      await new Promise((r) => setTimeout(r, 400));
      if (book.title.trim() === "") return { status: 400, body: { error: { details: [{ field: "title", message: "Title is required" }] } } };
      if (taken.includes(book.isbn)) return { status: 409, body: { error: { details: [{ field: "isbn", message: "Already in use" }] } } };
      return { status: 201, body: { id: "6afb08ef648a6cdddc0c3da5", ...book } };
    }

    const $ = (sel) => document.querySelector(sel);
    const show = (field, msg) => { $("#" + field + "-err").textContent = msg; };
    for (const field of ["title", "isbn"]) {
      document.getElementById(field).addEventListener("input", () => show(field, "")); // editing clears the old error
    }

    document.querySelector("#f").addEventListener("submit", async (e) => {
      e.preventDefault();
      const book = { title: $("#title").value, isbn: $("#isbn").value };
      let ok = true;
      for (const [field, rule] of Object.entries(clientRules)) {
        const msg = rule(book[field]);
        show(field, msg);
        if (msg) ok = false;
      }
      if (!ok) { $("#log").textContent = "Blocked in the browser. No request sent."; return; }
      const res = await fakeApi(book);
      if (res.status === 201) { $("#log").textContent = "Saved with id " + res.body.id; return; }
      for (const d of res.body.error.details) show(d.field, d.message);
      $("#log").textContent = "The server answered " + res.status + ".";
      console.log(res.status, res.body.error.details);
    });
  </script>
</body>
</html>

Save shows the format error with "No request sent". Typing 9789300000011 and saving gives "Already in use" from the fake server, with status 409. Any other 13-digit ISBN saves. Try a title of three spaces: the client rule passes it, the server does not.

The same form with typed reactive forms

In a project that already uses reactive forms, keep them; the server-error idea is the same. With nonNullable: true, getRawValue() has exactly the BookInput type, and setErrors() attaches a server message to a control:

TypeScript
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';

protected readonly bookForm = new FormGroup({
  title: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.maxLength(200)] }),
  author: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.maxLength(120)] }),
  isbn: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.pattern(/^\d{13}$/)] }),
  category: new FormControl<Category>('Literature', { nonNullable: true }),
  copies: new FormControl(1, { nonNullable: true, validators: [Validators.min(1), Validators.max(50)] }),
});

save() {
  const input: BookInput = this.bookForm.getRawValue();
  this.api.create(input).subscribe({
    error: (err: HttpErrorResponse) => {
      const body = err.error as Partial<ApiErrorBody> | null;
      for (const d of body?.error?.details ?? []) {
        this.bookForm.get(d.field)?.setErrors({ server: d.message });
      }
    },
  });
}

We compiled this version with tsc against the same project to confirm the types line up. The template binds with [formGroup] and formControlName, as the Reactive Forms lesson shows.

Common mistakes

  • Trusting the client rules. They are a comfort for honest users. The API must keep every rule, and here it caught the blank title that the form missed.
  • Showing err.message. For HTTP errors it is a technical line. Show the API's details or error.message.
  • Putting books/:id before books/new. The router then treats new as an id.
  • Reading inputs in the constructor. The id input is still empty there; use ngOnInit, computed or a resource.
  • General errors as form errors. A form-level error keeps the form invalid, so Save stops working until a field changes.

Interview questions

1. Should you use Signal Forms or reactive forms in Angular 22?

Both are stable in Angular 22. Signal Forms suit new, signal-based apps: the data is a signal model and every field state is a signal. Reactive forms are the long-standing choice and appear in most existing projects, so a team usually keeps them there and uses Signal Forms for new code.

2. Why validate the same rule in the form and on the server?

The form check gives instant feedback and saves a round trip. The server check is the real protection, because requests can come from curl, scripts or a modified page. Some rules, such as a unique ISBN, can only be checked on the server.

3. How do you show a server validation error under the right input?

The API returns a stable error shape with a field name per problem. The client maps each name to its form control (with setErrors() in reactive forms, or by returning errors with a fieldTree from a Signal Forms submit action). Messages with no matching field go to a general message area.

4. What is the CORS preflight you see before some POST requests?

For cross-origin requests that are not "simple", such as a POST with Content-Type: application/json, the browser first sends an OPTIONS request asking whether the method and headers are allowed. The real request follows only if the server's CORS answer permits it.

Key points

  • Signal Forms are stable in Angular 22 (@publicApi 22.0); LibTrack uses them, and typed reactive forms remain a good choice in existing code.
  • The model is a signal typed with the shared BookInput, so the form follows the API contract.
  • Client rules mirror the Zod rules and messages; the server still checks everything.
  • serverErrors() turns details (and known codes such as COPIES_ON_LOAN) into errors on the right fields.
  • General errors such as 401 go to a separate saveError signal.
  • One BookForm serves /books/new and /books/:id/edit; its routes come before books/:id.

Exercise

Build a "new member" form for librarians at /members/new using the MemberInput type from the CRUD lesson's exercise. Require a name of 2 to 80 characters, a valid email, a roll number of letters, digits and hyphens, and a type of student or faculty. Send it with a MembersApi.create() method. When the API answers 409 because the email is already registered, show the message under the email input.

Show solution
TypeScript
// members/member-form/member-form.ts (the important parts)
protected readonly model = signal<MemberInput>({ name: '', email: '', rollNo: '', type: 'student' });
protected readonly saveError = signal('');

protected readonly memberForm = form(this.model, (m) => {
  required(m.name, { message: 'Name is required' });
  minLength(m.name, 2, { message: 'Name is too short' });
  maxLength(m.name, 80, { message: 'Name is too long' });
  required(m.email, { message: 'Email is required' });
  email(m.email, { message: 'Enter a valid email address' });
  pattern(m.rollNo, /^[A-Za-z0-9-]{3,20}$/, { message: 'Use letters, digits and hyphens' });
}, {
  submission: {
    action: async (fields) => {
      this.saveError.set('');
      try {
        await firstValueFrom(this.api.create(this.model()));
        await this.router.navigate(['/members']);
        return null;
      } catch (err) {
        const fieldErrors = serverErrors(err, fields);
        if (fieldErrors.length === 0) this.saveError.set(apiErrorMessage(err));
        return fieldErrors;
      }
    },
  },
});

No extra code is needed for the duplicate email. The server's toApiError() turns MongoDB's duplicate key error into details: [{ field: "email", message: "Already in use" }], and serverErrors() puts it under the email input. Add the route before any members/:id route, and use a <select [formField]="memberForm.type"> for the type.

Quick Quiz

1. Why does the server still check rules that the Angular form already checks?

2. A librarian types a title of three spaces. What happens in LibTrack?

3. Which rule can only the server check?

4. Why does books/new have to come before books/:id in the routes?

Learn MEAN 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