Sub topic 13
Validating across several fields
What you need first
This chapter assumes you can build a template-driven form with ngModel, read control state through template reference variables such as #f="ngForm", and write a validator directive that registers itself under NG_VALIDATORS. If the validator directive is unfamiliar, review the chapter on custom validators first.
Why a single-control validator is not enough
A validator attached to one ngModel input receives only that control. Rules that compare values, such as "confirm password must equal password" or "end date must not be before start date", need to read two controls at once. Angular offers three ways to do this in template-driven forms.
| Where the validator runs | How you attach it | Where the error appears | Revalidates when the sibling changes |
|---|---|---|---|
| On the group or form | Directive on `ngModelGroup` or `<form>` | On the group or form (`errors`) | Yes, because any child change revalidates the parent |
| On one control, reading a sibling through `control.parent` | Directive on the input | On that control | No, unless you trigger it yourself |
| On one control, with the other value passed as an input | Directive with `[matchField]="other"` | On that control | Yes, if the directive notifies Angular |
The group-level approach is the most reliable. The other two are useful when you want the error to sit on a specific field.
A group-level validator
A group validator receives the group as an AbstractControl. You read the children with group.get('name'). The child name is the value of the name attribute on the input.
import { Directive } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: '[passwordMatch]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: PasswordMatchDirective, multi: true },
],
})
export class PasswordMatchDirective implements Validator {
validate(group: AbstractControl): ValidationErrors | null {
const password = group.get('password')?.value;
const confirm = group.get('confirm')?.value;
// Let the per-field "required" validators report empty values.
if (!password || !confirm) {
return null;
}
return password === confirm ? null : { passwordMismatch: true };
}
}Two details matter here:
- The directive returns
nullwhen either field is empty. Otherwise the user sees a "does not match" message while still typing the first field, and the mismatch error duplicates therequirederror. - The directive does not care what element it sits on. Put it on an
ngModelGroupelement and Angular registers it as a validator of that group. Put it on the<form>element and it validates the whole form.
Now use it in a component. The passwordMatch attribute goes on the element that carries ngModelGroup.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { PasswordMatchDirective } from './password-match.directive';
@Component({
selector: 'app-set-password',
imports: [FormsModule, PasswordMatchDirective],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<div ngModelGroup="credentials" passwordMatch #cred="ngModelGroup">
<label for="password">Password</label>
<input
id="password"
name="password"
type="password"
[(ngModel)]="model.password"
#password="ngModel"
required
minlength="8"
/>
<label for="confirm">Confirm password</label>
<input
id="confirm"
name="confirm"
type="password"
[(ngModel)]="model.confirm"
#confirm="ngModel"
required
/>
@if (cred.errors?.['passwordMismatch'] && (confirm.dirty || confirm.touched)) {
<p role="alert">The two passwords do not match.</p>
}
</div>
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class SetPasswordComponent {
model = { password: '', confirm: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Reading the result
The mismatch error is on the group, not on either input. After the user types different values:
cred.errorsis{ passwordMismatch: true }.cred.invalidistrue, sof.invalidis alsotrueand the Save button is disabled.confirm.errorsisnull, because the confirm input has no error of its own.
This is why the template reads cred.errors?.['passwordMismatch'] and not confirm.errors. The bracket syntax is required because errors is typed as an index signature, and strict templates reject dot access on it.
Choosing when to show the message
The message is gated on confirm.dirty || confirm.touched. Without this gate, the group would show an error as soon as both fields hold different non-empty values, including while the user is still typing the confirm field. If you prefer to wait until the user leaves the field, check confirm.touched alone.
A form-level validator
Use the same directive class on <form> when the rule spans controls that are not in one group, for example start and end dates in different sections. Change the selector to form[dateRange] or keep an attribute selector and put it on the form. The values then sit at the top level, or under their group names, so adjust the get paths. With nested groups, group.get('dates.start') accepts a dotted path.
import { Directive } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: 'form[dateRange]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: DateRangeDirective, multi: true },
],
})
export class DateRangeDirective implements Validator {
validate(form: AbstractControl): ValidationErrors | null {
const start = form.get('start')?.value as string | null;
const end = form.get('end')?.value as string | null;
if (!start || !end) {
return null;
}
// ISO date strings (yyyy-mm-dd) compare correctly as text.
return end >= start ? null : { dateRange: { start, end } };
}
}The error is then available as f.errors?.['dateRange']. The error object can carry the offending values, which lets a message name them.
Putting the error on one control
Sometimes a design requires the error to belong to the confirm field, for example so confirm.invalid styles only that input through the ng-invalid CSS class. A control-level validator can read a sibling through control.parent, but there is a catch. Angular revalidates a control only when that control's own value changes. If the user edits password after confirm, the confirm control keeps its old validity.
The fix is to pass the other value in as a directive input and tell Angular to revalidate when it changes. The Validator interface has an optional registerOnValidatorChange method for this purpose.
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import {
AbstractControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
@Directive({
selector: '[matchField]',
standalone: true,
providers: [
{ provide: NG_VALIDATORS, useExisting: MatchFieldDirective, multi: true },
],
})
export class MatchFieldDirective implements Validator, OnChanges {
@Input('matchField') other: unknown;
private revalidate: () => void = () => {};
validate(control: AbstractControl): ValidationErrors | null {
if (!control.value) {
return null;
}
return control.value === this.other ? null : { matchField: true };
}
registerOnValidatorChange(fn: () => void): void {
this.revalidate = fn;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['other']) {
this.revalidate();
}
}
}In the template, bind the other field's model value:
<input name="password" type="password" [(ngModel)]="model.password" required />
<input
name="confirm"
type="password"
[(ngModel)]="model.confirm"
[matchField]="model.password"
#confirm="ngModel"
/>
@if (confirm.errors?.['matchField'] && (confirm.dirty || confirm.touched)) {
<p role="alert">The passwords do not match.</p>
}When model.password changes, Angular updates the other input, ngOnChanges runs, and revalidate makes the confirm control run its validators again.
Common errors
- The error never appears. The directive is not in the component's
importsarray, so the attribute is ignored silently. Check the imports first. - The group is always valid. The
nameattributes do not match the keys passed togroup.get(...). A typo returnsnullfromget, and optional chaining turns that intoundefined, so the validator returnsnull. - The submit button stays enabled. The error is on the group, but the button checks a single control. Bind
[disabled]tof.invalid, which covers every level. - The message flashes while typing. The template checks only the group error. Add
dirtyortouchedof the field being edited. - The error looks stale after editing the sibling. You used a
control.parentvalidator without the revalidation hook shown above. Move to a group validator or add the input binding.
Choosing an approach
Prefer the group validator when the rule is about the pair as a whole, since revalidation is automatic and one place owns the error. Use the control-level directive with an input when the UI needs the field itself to be marked invalid. If you find yourself writing many cross-field rules, or rules that depend on several groups, reactive forms handle them more directly with a validator passed to FormGroup, and that is a reasonable signal to switch.
Exercise
A form has an ngModelGroup named "range" containing inputs with name="min" and name="max". Write the body of a validate(group) method for a group-level directive that returns { rangeInvalid: true } when max is smaller than min, and null otherwise. What must it do when either value is empty, and why?
Show answer
const min = group.get('min')?.value; const max = group.get('max')?.value; if (min === null || min === '' || max === null || max === '' || min === undefined || max === undefined) { return null; } return Number(max) < Number(min) ? { rangeInvalid: true } : null; It returns null for empty values so the required validators on each input report missing values, and so no range error shows before the user has entered both numbers. The numbers are converted with Number because text inputs without type="number" produce strings, and comparing strings gives wrong results ("9" is greater than "10" as text). Note that 0 is a valid value, so the emptiness check must not treat 0 as missing.
Exercise
Your confirm-password input uses a validator that reads control.parent.get('password'). The user types a password, types a matching confirmation, then changes the password. Why does the confirm field still look valid, and what are two ways to fix it?
Show answer
Angular reruns a control's validators only when that control's value changes, so editing password does not revalidate confirm. One fix is to move the rule into a group-level validator on ngModelGroup or the form, which revalidates whenever any child changes. The other is to bind the password value into the directive as an input, such as [matchField]="model.password", and call the function passed to registerOnValidatorChange from ngOnChanges so the control revalidates.