Skip to the page

Angular forms and routing · Build it

Build cross-field and async validators

The interviewer asks

On a signup form, write a validator that checks 'confirm password' matches 'password', and an async validator that checks whether the username is taken by calling /api/users/exists. Show the error messages in the template.

Then

Follow-ups the interviewer asks next

  1. Why put the match check on the group and not on the confirm control?
  2. The async validator sends a request on every key press. How do you fix that?
  3. What's the form's status while the check runs?
  4. How would this look in signal forms?
  5. How do you test a validator?

The answer

What a strong answer covers

  • Cross-field ValidatorFn on the group: (g: AbstractControl): ValidationErrors | null => g.get('password')?.value === g.get('confirm')?.value ? null : { mismatch: true }, set with { validators: passwordsMatch }.
  • Async: an AsyncValidatorFn factory that takes the API, e.g. usernameFree(api) returning c => timer(400).pipe(switchMap(() => api.exists(c.value)), map(taken => taken ? { taken: true } : null), catchError(() => of(null))). Angular cancels the previous check when the value changes, so the timer acts as a debounce. updateOn: 'blur' is another option.
  • Status is PENDING while it runs; disable submit while form.pending.
  • Template: @if (form.hasError('mismatch') && form.controls.confirm.touched) { … }.
  • Signal forms: a validate(...) rule that reads the other field, and validateHttp with the debounce option (v22).
  • Validators are plain functions: test them with a FormControl or FormGroup, no TestBed.
  • The server still checks at submit; the async check is only for user experience.

The red pen

Common traps

Avoid:an async validator with no debounce; the mismatch error shown on the wrong field; forgetting to return null when valid.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview