Sub topic 13
Validating across several fields
This chapter assumes you know built-in validators, custom validator directives, NgForm, and ngModelGroup. Some rules involve more than one control. Examples are "confirm password must match password" and "end date must follow start date". A validator attached to a single ngModel only sees that control's value, so it can't enforce these rules.
Put the validator on a parent
The fix is to attach the validator to a container. In a template-driven form, two containers can hold a validator: an ngModelGroup and the ngForm itself. Both are backed by a FormGroup. A validator on a group receives that group as its AbstractControl argument. It can then read the children with control.get('name').
A group validator directive
The directive registers under NG_VALIDATORS, as in the custom validator chapter. The only difference is that validate reads two children instead of one value.
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;
return password && confirm && password !== confirm
? { passwordMismatch: true }
: null;
}
}The optional chaining (?.) matters. Angular may run the group validator before the child controls are registered, so group.get(...) can return null on the first pass.
Apply it to the group
Place the directive on the same element as ngModelGroup. Export the group with a reference variable to read its errors.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { PasswordMatchDirective } from './password-match.directive';
@Component({
selector: 'app-register',
imports: [FormsModule, PasswordMatchDirective],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<div ngModelGroup="credentials" #cred="ngModelGroup" passwordMatch>
<label for="password">Password</label>
<input id="password" name="password" type="password"
[(ngModel)]="model.password" required minlength="8" />
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password"
[(ngModel)]="model.confirm" required />
</div>
@if (cred.errors?.['passwordMismatch'] && cred.dirty) {
<p role="alert">Passwords do not match.</p>
}
<button type="submit" [disabled]="f.invalid">Register</button>
</form>
`,
})
export class RegisterComponent {
model = { password: '', confirm: '' };
onSubmit() {
console.log('Registered', this.model);
}
}The error belongs to the group, so the message reads cred.errors, not confirm.errors. Because f.invalid includes the validity of every nested group, the submit button stays disabled while the passwords differ.
Group or whole form
| Placement | Validator receives | Error is read from |
|---|---|---|
| `ngModelGroup` element | The group's `FormGroup` | The group reference (`#cred`) |
| `<form>` element | The whole form's `FormGroup` | `f.errors` |
Prefer a group when the rule involves a known subset of fields. It keeps the error scoped and lets you reuse the same group in other forms.
Common mistakes
- Reading the wrong object. Look for the error on the group reference, not on an individual
ngModel. - Forgetting the
nameattribute on children. Without it,group.get('confirm')finds nothing. - Returning an error while a field is still empty. Return
nulluntil both values exist, and letrequiredreport the empty case.
Exercise
A form has a ngModelGroup="dates" containing start and end inputs. Sketch the validate method of a directive that reports { endBeforeStart: true } when both dates are filled in and end is earlier than start. Where do you read the error in the template?
Show answer
validate(group: AbstractControl): ValidationErrors | null { const s = group.get('start')?.value; const e = group.get('end')?.value; return s && e && e < s ? { endBeforeStart: true } : null; } (ISO date strings such as 2026-11-26 compare correctly as strings.) Register it under NG_VALIDATORS with multi: true, put its selector on the ngModelGroup element, and export the group with #dates="ngModelGroup". Read dates.errors?.['endBeforeStart'] in the template.