Sub topic 14
Validating Fields Against Each Other
Some rules depend on more than one field. A confirmation password must equal the password. An end date must not come before a start date. A validator attached to a single FormControl sees only that control's value, so it can't check rules like these reliably. In Angular you attach such rules to the FormGroup that contains the fields.
This chapter assumes you can already write a synchronous ValidatorFn, build typed FormGroups, and read touched, dirty, and errors to show messages in a template.
Where a Cross-Field Validator Lives
A FormGroup is also an AbstractControl, so it accepts validators the same way a FormControl does. You pass them in the second argument of the constructor. The validator receives the group itself, and it reads the child controls with group.get('name').
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn } 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 };
};
export const signupForm = new FormGroup(
{
password: new FormControl('', { nonNullable: true }),
confirmPassword: new FormControl('', { nonNullable: true }),
},
{ validators: passwordsMatch },
);The error goes on the group and not on either child. signupForm.hasError('passwordsMismatch') is true, while signupForm.controls.confirmPassword.valid can still be true. This difference matters when you display the error, which a later section covers.
How Validation Order Works
When a child's value changes, Angular runs that child's validators first. The update then moves up the tree: the parent recomputes its value and runs its own validators, and its parent does the same, up to the root. That order is why the group validator always sees current child values. It is also why the rule re-runs no matter which of the two fields the user edits.
A Reusable Validator Factory
Hard-coded control names tie a validator to one form. A factory function takes the names as parameters, so one validator works across many forms. It also returns null when a control is missing or the confirmation field is still empty. Without that check, the form reports "passwords don't match" before the user has typed anything in the second field.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function fieldsMatch(source: string, target: string, errorKey = 'fieldsMismatch'): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const a = group.get(source);
const b = group.get(target);
if (!a || !b || !b.value) {
return null;
}
return a.value === b.value ? null : { [errorKey]: true };
};
}
export const dateRange: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
const start: string = group.get('start')?.value ?? '';
const end: string = group.get('end')?.value ?? '';
if (!start || !end) {
return null;
}
return start <= end ? null : { dateRange: { start, end } };
};The dateRange validator compares strings on purpose. An <input type="date"> produces values in YYYY-MM-DD form, and strings in that form sort in date order. Its error object carries the two values, so the template can show them in the message.
Displaying a Group-Level Error
The error lives on the group, but the user is looking at an input. Combine the group's error with the touched state of the field that relates to it. Usually that is the second field.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { fieldsMatch } from './fields-match.validator';
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input type="password" formControlName="password" placeholder="Password" />
<input
type="password"
formControlName="confirmPassword"
placeholder="Confirm password"
[attr.aria-invalid]="showMismatch"
aria-describedby="mismatch-msg"
/>
@if (showMismatch) {
<p id="mismatch-msg">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, Validators.minLength(8)] }),
confirmPassword: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
},
{ validators: fieldsMatch('password', 'confirmPassword', 'passwordsMismatch') },
);
get showMismatch(): boolean {
return this.form.hasError('passwordsMismatch') && this.form.controls.confirmPassword.touched;
}
submit(): void {
console.log(this.form.getRawValue());
}
}Common Mistakes
Calling setErrors on a child from the group validator
It looks convenient to call group.get('confirmPassword')?.setErrors({ mismatch: true }) inside the group validator so the error appears on the input. The problem is that the child's own validators overwrite that error the next time the child validates. If you also clear it with setErrors(null), you erase real errors such as required. Keep the group validator pure: return an error object and change nothing else.
Putting the rule on the child and reading the parent
A validator on confirmPassword could read control.parent?.get('password'). It runs only when confirmPassword changes, though. If the user edits password afterwards, the error goes stale. On the first validation control.parent is also null, because Angular validates the control before it attaches it to the group. A group validator has neither problem.
Forgetting disabled controls
group.value leaves out disabled children, but group.get('x')?.value still returns their values. If a disabled field should not take part in the rule, check control.disabled inside the validator.
Comparing the wrong types
The value of <input type="number"> is a number, but text inputs and patched API data can give you strings. Compare '10' and 10 with === and you get a mismatch. Convert both values to one type before you compare them.
Choosing an Approach
| Approach | Re-runs when either field changes | Error location | Recommended |
|---|---|---|---|
| Validator on the parent group | Yes | Group | Yes |
| Child validator reading `control.parent` | No | Child | No |
| Group validator calling `setErrors` on a child | Yes, but child validation overwrites the error | Child | No |
If a rule involves fields from different branches of a nested form, put the validator on the nearest group that contains all of them.
Exercise
A booking form has checkIn and checkOut date controls in a group. Write a group validator stayLength(maxNights: number) that returns { tooLong: { nights } } when the stay runs longer than maxNights, and returns null when either date is empty. Why should it be a group validator and not a validator on checkOut?
Show answer
export function stayLength(maxNights: number): ValidatorFn { return (group: AbstractControl): ValidationErrors | null => { const inDate = group.get('checkIn')?.value; const outDate = group.get('checkOut')?.value; if (!inDate || !outDate) { return null; } const nights = (Date.parse(outDate) - Date.parse(inDate)) / 86_400_000; return nights > maxNights ? { tooLong: { nights } } : null; }; } It belongs on the group because the group re-validates after either child changes. A validator on checkOut would not re-run when the user edits checkIn, so its result could go stale.
Exercise
Your group validator works, but the red-border CSS rule input.ng-invalid never highlights the confirmation field when the passwords differ. Why, and how do you fix it?
Show answer
The passwordsMismatch error belongs to the FormGroup, so ng-invalid is applied to the form element and not to the input. The input's own control is still valid. Fix it by binding a class or aria-invalid on the input from form.hasError('passwordsMismatch'), combined with the field's touched state. Don't call setErrors on the child, because the child's validators overwrite that error.