October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Build Cross-Field Validators in Angular Forms

Compare sibling fields in Angular by attaching a validator to their common FormGroup, returning a named error or null, and displaying the error from the group.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a reactive Angular form, put a validator that compares sibling fields on their nearest common FormGroup. Read the child controls from the group and return either null when the combination is valid or a ValidationErrors object when it is not. The group then owns the error, so the template should check and display it on the group.

Reactive forms: validate related fields on their common group

A cross-field rule accepts or rejects a combination of values from different form fields—for example, when two fields must not match. Angular’s cross-field validation guide demonstrates this with sibling controls named name and role. Attach the validator to the FormGroup that contains the fields, rather than validating either field in isolation.

As an Amazon Associate I earn from qualifying purchases.

Define a validator that returns a group error

A synchronous validator receives the control it is attached to. For a group-level validator, retrieve the child controls with get(), compare their values, and return an error map for an invalid combination or null for a valid one:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const unambiguousRoleValidator: ValidatorFn =
  (control: AbstractControl): ValidationErrors | null => {
    const name = control.get('name');
    const role = control.get('role');

    if (!name || !role) {
      return null;
    }

    return name.value === role.value
      ? { unambiguousRole: true }
      : null;
  };

The !name || !role check makes the validator safe if it is reused with a group that does not contain both controls. Adapt the comparison and error key to the rule your form needs.

Attach it when constructing the form

Pass the validator in the options for the group that contains the compared controls:

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

actorForm = new FormGroup(
  {
    name: new FormControl(''),
    role: new FormControl(''),
  },
  { validators: unambiguousRoleValidator },
);

Angular’s FormGroup API supports a validator function, an array of validators, or an options object containing validators and a validation trigger. If the fields are inside a nested group, attach the rule to the group that is their nearest common ancestor.

Display the error where it belongs

Because the validator is attached to actorForm, the error belongs to that group. Check the group with hasError() and, as in Angular’s documented example, wait until the group has been touched or changed before showing the message:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<div [formGroup]="actorForm">
  <label>
    Name
    <input formControlName="name">
  </label>

  <label>
    Role
    <input formControlName="role">
  </label>

  <div
    *ngIf="actorForm.hasError('unambiguousRole') && (actorForm.touched || actorForm.dirty)"
    role="alert">
    Name and role must be different.
  </div>
</div>

Showing the message beside the related fields or in a group-level error area makes the relationship clear. Avoid setting or removing errors on child controls inside the group validator as a shortcut: the documented pattern keeps the cross-field error on the group and renders it from there.

Template-driven forms: register a validator directive

Template-driven forms use a different registration pattern. Angular’s form validation guide describes wrapping the validator function in a directive and providing that directive through NG_VALIDATORS. This lets Angular discover the validator through the template-driven form system; it is not the same as attaching a function in a reactive form’s model.

Form approach Where validation logic is declared How it is registered
Reactive In the component’s form model; a rule comparing siblings belongs on their common FormGroup. Pass the validator function or an array of functions in the group options.
Template-driven In a directive that wraps the validator function. Provide the directive through NG_VALIDATORS.

When the rule needs asynchronous validation

Use an asynchronous validator when checking a combination requires an asynchronous result, such as a remote lookup. Angular’s validation guide states that asynchronous validators run only after synchronous validators pass, and each asynchronous validator must complete before Angular sets errors. Async validators return a Promise or Observable that emits an error map or null; synchronous validators return an error map or null.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep the error key and owner consistent

Choose a descriptive error key, such as unambiguousRole, and use that same key when checking the group in the template. With this ownership model, the validator reports whether the fields are invalid together, while each individual control can continue to report its own field-level errors.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.