Sub topic 7
Validating several fields together
This chapter assumes you can write a basic validator function, attach validators to a FormControl, and read control state in a template. It builds on the validator contract: a function that receives a control and returns ValidationErrors or null.
Why a control validator is not enough
A validator attached to one control sees only that control's value. Some rules compare fields. "Password and confirmation must match" and "end date must be after start date" are examples. Neither field is wrong on its own. The pair is wrong.
The fix is to attach the validator to the parent FormGroup. A group is an AbstractControl, so a ValidatorFn works there unchanged. The only difference is what you do with the argument: you read the children with group.get(...).
A group-level validator
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 };
};
// Usage:
// new FormGroup(
// { password: new FormControl(''), confirm: new FormControl('') },
// { validators: passwordsMatchValidator },
// );Three details matter here:
- The parameter type is
AbstractControl, because that is whatValidatorFndeclares. Usegroup.get('name')to reach a child. The optional chaining (?.) handles a name that does not exist. - The error is returned for the group, not for either child.
form.hasError('passwordsMismatch')istrue.form.controls.confirm.hasError('passwordsMismatch')isfalse. - The second argument to
FormGroupis an options object. Pass the validator asvalidators. Pass an array if you have several.
How validation flows
Angular runs each child's validators first and then the group's validators. Whenever any child value changes, the group revalidates.
The group's status depends on its children too. If any child is invalid, the group is invalid even when the group validator returns null. Group errors live in form.errors. Child errors stay on the child.
Showing the group error
Because the error sits on the group, the template checks the group. It still makes sense to wait until the user has interacted with the confirmation field.
<form [formGroup]="form">
<input type="password" formControlName="password" />
<input type="password" formControlName="confirm" />
@if (form.hasError('passwordsMismatch') && form.controls.confirm.touched) {
<p>Passwords do not match.</p>
}
</form>The group's own touched flag is not a good gate. It becomes true only after one of its children is touched, which may be the password field. Checking the specific child gives better timing.
Putting the error on a child instead
Some teams prefer the error to appear on the field that the user must fix. A group validator can do this with setErrors, but it is a side effect inside a validator, and it has a catch: the child's own validators will not rerun until its value changes, so the manual error can go stale. Prefer the group-level error and read it from the template. If you need the error on the child, set it deliberately and clear it when the rule passes.
Common mistakes
- Checking
confirm.errorsfor a group error. The key is inform.errors, so the message never shows. - Returning an error while a field is empty. If
passwordandconfirmare both empty, the example returnsnullbecause the values are equal. Leave the "required" rule toValidators.requiredon each child so rules stay separate. - Assuming
group.get('x')always exists. A typo in the control name returnsnull, andnull?.valueisundefined. Two typos can make both sidesundefined, which compare as equal and hide the bug. A unit test prevents this. - Forgetting the group runs on every child change. Keep the validator cheap and free of network calls. Use an async validator for those.
A date range example
The same pattern applies to any pair of fields. This validator returns an error when the end date is before the start date. ISO date strings (2026-03-01) compare correctly as text.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const dateRangeValidator: ValidatorFn = (
group: AbstractControl,
): ValidationErrors | null => {
const start = group.get('start')?.value;
const end = group.get('end')?.value;
if (!start || !end) {
return null;
}
return end >= start ? null : { dateRange: { start, end } };
};The error value carries both dates, so a template can show them. The early return null skips the check while either field is empty, which leaves "required" to the child validators.
Exercise
A form has a FormGroup with password and confirm controls and passwordsMatchValidator attached to the group. The template shows @if (form.controls.confirm.hasError('passwordsMismatch')) and the message never appears when the values differ. Why, and what is the fix?
Show answer
The validator is attached to the group, so its error is stored in the group's errors, not on the confirm control. Check form.hasError('passwordsMismatch') instead, optionally combined with form.controls.confirm.touched so the message waits for user interaction.
Exercise
Write the options object that attaches both passwordsMatchValidator and dateRangeValidator to one FormGroup.
Show answer
{ validators: [passwordsMatchValidator, dateRangeValidator] }, passed as the second argument to new FormGroup(...). Angular merges the errors from every validator that fails into form.errors.