Sub topic 13
Validating Fields Against Each Other
This chapter assumes you can already build a typed FormGroup, bind it with formGroupName and formControlName, and write a synchronous ValidatorFn. Some rules involve more than one field. "Confirm password must match password" and "end date must follow start date" are common examples. A validator on a single control can't see its siblings, so these rules belong on the parent group.
How Group Validators Work
A validator attached to a FormGroup receives the group itself as its AbstractControl argument. It can read any child with group.get('name') and return one error object for the whole group. Angular runs each child's validators first and then runs the group's validators. It repeats this whenever any child value changes.
Writing and Attaching the Validator
import { Component } from '@angular/core';
import {
AbstractControl, FormControl, FormGroup, ReactiveFormsModule,
ValidationErrors, ValidatorFn, Validators,
} from '@angular/forms';
export const passwordsMatch: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
const password = group.get('password')?.value;
const confirm = group.get('confirmPassword')?.value;
return password === confirm ? null : { passwordsMismatch: true };
};
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<input type="password" formControlName="password" />
<input type="password" formControlName="confirmPassword" />
@if (form.hasError('passwordsMismatch') && form.controls.confirmPassword.touched) {
<p>Passwords do not match.</p>
}
<button type="submit" [disabled]="form.invalid">Sign up</button>
</form>
`,
})
export class SignupComponent {
form = new FormGroup(
{
password: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
confirmPassword: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
},
{ validators: passwordsMatch },
);
}The second argument to new FormGroup is an options object, and validators goes inside it. With FormBuilder you would write fb.group({...}, { validators: passwordsMatch }).
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Checking `form.controls.confirmPassword.hasError('passwordsMismatch')` | The message never appears | Check `form.hasError('passwordsMismatch')`, because the error lives on the group |
| Attaching the validator to `confirmPassword` | The rule does not re-run when `password` changes | Attach it to the group, which re-runs on any child change |
| Showing the error as soon as the page loads | Users see an error before they type anything | Gate the message on the relevant child's `touched` or `dirty` state |
| Expecting `confirmPassword` to get the `ng-invalid` CSS class | The input isn't styled red | Style based on the group's state, or bind a class to `form.hasError(...)` |
Exercise
Write a group validator dateRange that returns { invalidRange: true } when a start Date is later than an end Date, and returns null when either date is missing.
Show answer
export const dateRange: ValidatorFn = (g: AbstractControl): ValidationErrors | null => { const start = g.get('start')?.value as Date | null; const end = g.get('end')?.value as Date | null; if (!start || !end) return null; return start > end ? { invalidRange: true } : null; }; Attach it with new FormGroup({ start: ..., end: ... }, { validators: dateRange }).
Exercise
A user fixes the password field so that it matches confirmPassword, but the mismatch message stays visible. The validator was attached to the confirmPassword control. Why does this happen?
Show answer
A control's validators run only when that control's own value changes. Editing password never re-runs a validator attached to confirmPassword. Move the validator to the parent group so that a change to either child triggers it.