Form validation: built-in and custom validators, and FormArray

Intermediate · 11 min

Attaching validators to a reactive form, writing your own, catching cross-field errors, and handling a dynamic list of controls.

Before thisReactive forms fundamentals

kudvenkat · 11 min

Form validation: built-in and custom validators, and FormArray

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by kudvenkatReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A validator is just a function: `(control: AbstractControl) => ValidationErrors | null` — `null` means valid, an errors object means invalid, with keys you choose yourself.
  • A cross-field validator (checking that two fields agree, say) has to sit on the enclosing FormGroup, not on either individual FormControl — a single control has no visibility into its siblings.
  • FormArray models a variable-length list of controls — add or remove entries at runtime with `.push()`/`.removeAt()`, instead of a fixed, hand-written set of FormControls.

A validator is a function, not a special object

email = new FormControl('', [Validators.required, Validators.email]);

Built-in validators like Validators.required and Validators.email are plain functions matching one shape: given a control, return null if it’s valid, or an object describing what’s wrong if it isn’t. That’s the entire contract — there’s no hidden magic to a validator beyond “a function that inspects a control and reports a verdict.”

function forbiddenUsername(control: AbstractControl): ValidationErrors | null {
  return control.value === 'admin' ? { forbiddenUsername: true } : null;
}

Writing your own validator means writing exactly this shape yourself. The key you choose in the returned object (forbiddenUsername here) becomes how your template checks for that specific error — email.hasError('forbiddenUsername') — and how you’d display a message tailored to it, as opposed to a single generic “this field is invalid” catch-all.

Cross-field validation has to live a level up

A single FormControl’s validator only ever sees that one control’s own value — it has no way to reach a sibling control, because it was never given a reference to anything beyond itself. Checking that two fields agree (a password and its confirmation, say) needs a validator attached to the FormGroup containing both, which does receive the whole group and can read every child’s current value:

function passwordsMatch(group: AbstractControl): ValidationErrors | null {
  const pw = group.get('password')?.value;
  const confirm = group.get('confirmPassword')?.value;
  return pw === confirm ? null : { passwordsMismatch: true };
}

form = this.fb.group(
  { password: [''], confirmPassword: [''] },
  { validators: passwordsMatch },
);

This is the single most common reason a custom validator “doesn’t work” for beginners — attaching the comparison logic to one of the individual controls, where it structurally can’t see the other one, instead of to the group that actually has visibility into both.

FormArray: a list of controls, not a fixed set

phoneNumbers = this.fb.array([new FormControl('')]);

addPhoneNumber() {
  this.phoneNumbers.push(new FormControl(''));
}

removePhoneNumber(index: number) {
  this.phoneNumbers.removeAt(index);
}
@for (phone of phoneNumbers.controls; track $index) {
  <input [formControl]="phone" />
}

Every form so far assumed a fixed, known set of fields. A FormArray is for the case where the number of fields isn’t fixed at all — a user adding as many phone numbers, line items, or tags as they want. It holds a list of controls instead of a named object of them, and .push()/.removeAt() grow and shrink that list at runtime, with the template’s @for block simply rendering however many controls currently exist.

Async validators: when checking validity means a network call

Every validator shown so far runs synchronously — it inspects the control’s current value and returns an answer immediately. Some validation genuinely can’t work that way: checking whether a username is already taken requires asking a server. Async validators handle exactly this, returning an Observable<ValidationErrors | null> instead of the value directly:

function usernameTaken(userService: UserService): AsyncValidatorFn {
  return (control: AbstractControl) =>
    userService.checkUsername(control.value).pipe(
      map((taken) => (taken ? { usernameTaken: true } : null)),
    );
}

username = new FormControl('', { asyncValidators: [usernameTaken(this.userService)] });

The control’s status is PENDING while the async check is in flight, then settles to VALID or INVALID once the observable emits — worth knowing specifically because a template checking .invalid naively, without also accounting for .pending, can show a stale validity state for the brief window the network call is still running.

This lesson’s video, from a long-running, widely trusted programming-education channel, covers building and validating custom validators directly; the two linked videos go further — one focused specifically on validating a FormArray as a whole, the other on async validators and dynamic fields together, both genuinely separate concerns from the synchronous, cross-field validation covered above.

Check yourself

  1. 01Why would a validator checking that `password` and `confirmPassword` match be attached to the FormGroup containing both fields, rather than to the `confirmPassword` FormControl directly?

    A single FormControl's validator function only ever receives that one control — it has no reference to any sibling control, so `confirmPassword`'s own validator couldn't read `password`'s current value even if it wanted to. The enclosing FormGroup's validator receives the whole group, with access to every child control's value, which is what a cross-field comparison actually needs.

  2. 02You need a form where a user can add or remove an arbitrary number of "phone number" fields. Why does a fixed set of individually-named FormControls not work for this?

    A fixed set of named controls (phone1, phone2, phone3...) bakes in a specific count ahead of time, with no way to add a fourth without changing the form's definition. FormArray instead holds a list of controls whose length can grow or shrink at runtime — `.push(new FormControl(''))` adds one, `.removeAt(i)` removes one — exactly the shape an unknown-length list of fields needs.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark