Sub topic 7
Validating several fields together
This chapter assumes you can write a synchronous validator function that returns a ValidationErrors object or null. It also assumes you can attach validators to a FormControl and build a FormGroup in a reactive form. Typed forms (Angular 14 or later) and the @if template syntax (Angular 17 or later) are used in the examples.
Why a control validator is not enough
A validator attached to a FormControl receives that one control. It can read control.value and nothing else. Many rules involve two or more fields:
- A password and its confirmation must be equal.
- A start date must not be after an end date.
- A minimum price must not exceed a maximum price.
- At least one of "phone" or "email" must be filled in.
A control validator cannot express these rules, because it has no reliable way to reach its siblings. The solution is to attach the validator to the parent FormGroup. A group is an AbstractControl too, so the validator contract is the same. The only difference is that the control you receive is the group, and you read the children from it.
A group-level validator
This validator compares two children of a group:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const passwordsMatchValidator: ValidatorFn = (
group: AbstractControl,
): ValidationErrors | null => {
const password = group.get('password')?.value;
const confirm = group.get('confirm')?.value;
return password === confirm ? null : { passwordsMismatch: true };
};Two details matter here:
group.get('password')returnsAbstractControl | null. The optional chaining?.keeps the validator from throwing if the group does not have that child. In that case the comparison seesundefinedon both sides and the validator reports no error.- The error is returned for the group, not for either child. It ends up in
group.errors, andpassword.errorsstays untouched.
You attach the validator in the options argument of the FormGroup constructor, not in the controls:
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
export const form = new FormGroup(
{
password: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(8)],
}),
confirm: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
},
{ validators: passwordsMatchValidator },
);Use validators for a single function or an array. Async validators go in asyncValidators, which is covered in a later chapter.
How the group runs its validators
The order of events when a user types in one of the children is:
- The child control runs its own validators and updates its own status.
- The parent group runs its validators against the current state of all children.
- The group computes its status from its own errors and from the status of every enabled child.
Several consequences follow from this:
- The group validator runs on every change of any child, even a child that your validator does not read. Keep group validators cheap.
- The group validator runs even when a child is already invalid. If
passwordfailsminLength, your validator still sees its value. form.invalidis true when a child is invalid or when the group has errors. To find out which one, checkform.errorsfor the group andform.controls.password.errorsfor the child.- Disabled children are skipped when the group computes its status. They also drop out of
group.value, butgroup.get('x')?.valuestill returns a disabled child's value. If you want to ignore disabled fields, checkcontrol.disabledyourself.
Showing the group error in the template
Group errors are read from the group, so the template calls hasError on the group. The check happens in the component template that holds the form:
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<label for="password">Password</label>
<input id="password" type="password" formControlName="password" />
<label for="confirm">Confirm password</label>
<input id="confirm" type="password" formControlName="confirm" />
@if (form.hasError('passwordsMismatch') && form.controls.confirm.touched) {
<p>The 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)],
}),
confirm: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
},
{ validators: passwordsMatchValidator },
);
}The condition uses form.controls.confirm.touched instead of the group's own state. A group becomes touched only when one of its children has been touched, and dirty only when one has changed. Tying the message to the field the user is working on avoids showing a mismatch error while they are still typing the first password. The mismatch also exists from the very first moment if only one field is empty, so waiting for interaction matters here.
hasError also accepts a path as a second argument. form.hasError('required', ['password']) asks about a child, and form.hasError('passwordsMismatch') asks about the group itself.
A reusable factory for two fields
Hard-coding 'password' and 'confirm' makes the validator useful in one form only. A validator factory takes the field names as parameters and returns the validator:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function fieldsMatchValidator(first: string, second: string): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const a = group.get(first)?.value;
const b = group.get(second)?.value;
return a === b ? null : { fieldsMismatch: { first, second } };
};
}You call it when you build the group: { validators: fieldsMatchValidator('password', 'confirm') }. The error value carries the field names, so a template can read form.getError('fieldsMismatch')?.first to build a message.
Rules that depend on order or presence
Not every cross-field rule is an equality test. A date range needs an ordering and has to tolerate empty fields:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const dateRangeValidator: ValidatorFn = (
group: AbstractControl,
): ValidationErrors | null => {
const start: string | null = group.get('start')?.value ?? null;
const end: string | null = group.get('end')?.value ?? null;
if (!start || !end) {
return null;
}
return start <= end ? null : { dateRange: { start, end } };
};This validator compares ISO date strings such as 2026-11-26, which is what an <input type="date"> produces. Strings in that format sort the same way the dates do, so the plain <= comparison is correct. If your controls hold Date objects, compare getTime() values instead.
The early return null follows a rule that applies to all validators: a validator checks one thing. If a field is empty, Validators.required reports that. The date range validator stays quiet until both values exist, so the user does not see two errors for one mistake.
The "at least one of phone or email" rule uses the same pattern:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function atLeastOneValidator(...names: string[]): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const hasValue = names.some((name) => {
const value = group.get(name)?.value;
return typeof value === 'string' ? value.trim().length > 0 : value != null;
});
return hasValue ? null : { atLeastOne: { fields: names } };
};
}Where to put the error
The validator contract gives you one choice that matters: the error lives on the group. Some designs want it on a child, for example to style the confirm input as invalid. The options compare like this:
| Approach | Where the error appears | Trade-off |
|---|---|---|
| Return the error from the group validator | `group.errors` | Simple and predictable. The template must check the group. |
| Read the group error and bind a CSS class in the template | The group, shown on a child | No extra code in the validator. A little logic in the template. |
| Call `setErrors` on a child from the group validator | `child.errors` | Easy to get wrong, as the next callout explains. |
To mark the confirm input as invalid without setErrors, bind a class from the group error:
<input
id="confirm"
type="password"
formControlName="confirm"
[class.invalid]="form.hasError('passwordsMismatch') && form.controls.confirm.touched"
/>Revalidation and nested groups
A group validator reruns whenever a child's value or status changes. That includes changes you make from code. When you call form.controls.password.setValue('x'), the group reruns its validators. A programmatic setValue with { emitEvent: false } still recalculates validity. Only updateValueAndValidity({ onlySelf: true }) stops the update from propagating to the parent.
The updateOn option affects timing. If you set updateOn: 'blur' on the group, its children inherit the setting, so the group validator reruns only when a field loses focus. If you set it on a single child, that child updates on its own schedule, and the group validator sees the new value only at that time.
Groups can nest. A validator on an inner group sees only that group's children. A validator on the outer group can reach deeper with a path: group.get('address.zip') or group.get(['address', 'zip']). Errors never bubble up as a merged object. Each level keeps its own errors, and only the status propagates upward. To find the error from a nested group, ask that group: form.get('address')?.hasError('dateRange').
Common mistakes
- Attaching the validator to a child control. The validator then receives the child, and
group.get('...')returnsnullfor every name. The validator reports no error and nothing fails visibly. - Putting the validators array as the second argument in the old style,
new FormGroup(controls, validatorFn). This still works but is deprecated in favor of the options object{ validators: ... }. - Showing the group error without a
touchedcheck, which displays a message before the user has typed anything. - Forgetting that
form.invalidmixes child and group errors, and telling the user "fix the passwords" when a different field is the cause. - Comparing objects or arrays with
===. Use a field-by-field comparison or convert to a primitive first.
Exercise
Write a group validator factory minLessThanMaxValidator(minName: string, maxName: string): ValidatorFn for numeric fields. It must return { minGreaterThanMax: { min, max } } when the min value is greater than the max value, and null otherwise. It must also return null when either value is null or an empty string. Then say where you attach it and which call you use in a template to check for the error.
Show answer
The factory reads both children with group.get, returns null when either value is null or '', and compares them as numbers.
export function minLessThanMaxValidator(minName: string, maxName: string): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const min = group.get(minName)?.value;
const max = group.get(maxName)?.value;
if (min === null || min === '' || max === null || max === '' || min === undefined || max === undefined) {
return null;
}
return Number(min) > Number(max) ? { minGreaterThanMax: { min, max } } : null;
};
}
Attach it to the parent group: new FormGroup({ min: ..., max: ... }, { validators: minLessThanMaxValidator('min', 'max') }). In the template, check form.hasError('minGreaterThanMax'), ideally combined with form.controls.max.touched so the message appears only after the user has interacted with the field.