Full answer
A control validator only sees its own value. A rule that involves two fields needs a validator at the group level.
Steps:
- Write a
ValidatorFnthat takes anAbstractControl(the group), reads the two child controls, and returnsnullif the rule passes or an error object such as{ passwordMismatch: true }if it fails. - Attach it to the group:
fb.group({ ... }, { validators: passwordsMatch }). - In the template, check
form.hasError('passwordMismatch'). The error is on the group, not on a control, soconfirm.errorsdoes not contain it. - Show the message only after the user has touched the confirmation field:
form.hasError('passwordMismatch') && confirm.touched.
Details:
- The group validator runs when any child value changes, so it stays in sync when the first password changes later.
- Return
nullwhen either field is empty, so thatrequiredshows its own message and you do not show two messages at once. - To show the error on the confirmation control (for styling), you can set an error with
confirm.setErrors(...)inside the validator, but this is fragile. Group-level errors with a computed message are cleaner. - Add
aria-describedbylinking the confirmation input to the message, androle="alert"on the message.
Other cross-field rules use the same pattern: end date after start date, minimum less than maximum, at least one of several checkboxes checked.
For rules that need the server (is this username free), use an async validator on the control instead.
typescript
import { Component, inject } from '@angular/core';
import { AbstractControl, FormBuilder, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
export const passwordsMatch: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
const password = group.get('password')?.value as string;
const confirm = group.get('confirm')?.value as string;
if (!password || !confirm) {
return null;
}
return password === confirm ? null : { passwordMismatch: true };
};
@Component({
selector: 'app-signup',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<label for="pw">Password</label>
<input id="pw" type="password" formControlName="password" />
<label for="pw2">Confirm password</label>
<input id="pw2" type="password" formControlName="confirm" aria-describedby="pw-error" />
@if (form.hasError('passwordMismatch') && form.controls.confirm.touched) {
<p id="pw-error" role="alert">Passwords do not match.</p>
}
<button [disabled]="form.invalid">Create account</button>
</form>
`,
})
export class SignupComponent {
private readonly fb = inject(FormBuilder);
readonly form = this.fb.nonNullable.group(
{
password: ['', [Validators.required, Validators.minLength(8)]],
confirm: ['', Validators.required],
},
{ validators: passwordsMatch },
);
}Angular 20.3, strict template check passes. A Karma test checks the mismatch and match cases through the form.
Key points
- Cross-field rules need a validator on the parent group.
- Return `null` when valid, or an error object when not.
- Read the error with `form.hasError(...)` on the group.
- Show messages after touch, and link them with `aria-describedby`.
Common mistakes
- Putting the comparison validator on one control, so it misses changes to the other.
- Looking for the error in `confirm.errors` when it is on the group.
- Showing "required" and "mismatch" at the same time.
Follow-ups
- How would you check that an end date is after a start date?
- How would you write an async validator for a username?
- How do you reuse the validator with different field names?
Tips
- Say why the group is the right place.
- Return `null` for empty fields.
- Mention accessibility of the error message.
Evaluation rubric
- Attaches a validator to the group.
- Reads the group error correctly.
- Handles empty fields and messages.