← Back to Angular, page 6

angular-0110 · Easy fresher

How do you validate two fields together, for example that a password and its confirmation match, in a reactive form?

Put the validator on the parent FormGroup, because a group validator can read all child controls. Return an error object when the values differ, and show the message when the group has the error and the confirmation field has been touched.

Full answer

A control validator only sees its own value. A rule that involves two fields needs a validator at the group level.

Steps:

  1. Write a ValidatorFn that takes an AbstractControl (the group), reads the two child controls, and returns null if the rule passes or an error object such as { passwordMismatch: true } if it fails.
  2. Attach it to the group: fb.group({ ... }, { validators: passwordsMatch }).
  3. In the template, check form.hasError('passwordMismatch'). The error is on the group, not on a control, so confirm.errors does not contain it.
  4. 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 null when either field is empty, so that required shows 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-describedby linking the confirmation input to the message, and role="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.