Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 74 ยท Forms

Validation and Custom Validators

Learn Angular form validation: built-in validators, custom sync validators, cross-field group validators, async validators, error messages and updateOn, with runnable stand-ins.

A form that accepts anything is not a form, it is a text file with extra steps. Validation is how Angular decides whether the values in a form are acceptable, and it is built around one idea that is easy to remember: a validator is just a function. It receives a control, looks at its value and returns either null (all good) or an object that describes what is wrong.

This lesson covers the built-in validators, writing your own, validating several fields together (the classic "passwords must match" rule), asynchronous validators that call a server, how to show good error messages, and updateOn, which controls when validation runs. It assumes you know reactive forms; the same validators also work with template-driven forms through directives.

The Angular code here is read-only, because the site can't run the Angular compiler. The runnable examples are stand-ins: hand-written validator functions and a tiny control that model the same rules, including the order in which sync and async validators run. They are not Angular's real classes.

What a validator is

In @angular/forms the two function types are:

TypeScript
type ValidatorFn = (control: AbstractControl) => ValidationErrors | null;
type AsyncValidatorFn = (control: AbstractControl) => Promise<ValidationErrors | null> | Observable<ValidationErrors | null>;

ValidationErrors is a plain object whose keys name the failed rules. The control is valid when the result is null. The control's errors property is the merge of what all its validators returned, and status becomes 'INVALID' if that merge is not empty.

You attach validators when you create the control, as the second argument (or in the validators option):

TypeScript
import { Validators } from '@angular/forms';

readonly form = this.fb.nonNullable.group({
  name: ['', [Validators.required, Validators.minLength(2)]],
  email: ['', [Validators.required, Validators.email]],
  age: [18, [Validators.min(13), Validators.max(120)]],
  zip: ['', Validators.pattern(/^\d{5}$/)],
  agree: [false, Validators.requiredTrue],
});

The built-in validators

Validators is a class with static members, so there is nothing to inject:

Validator Passes when Error object when it fails
required the value is not empty (not '', null, undefined or an empty array) { required: true }
requiredTrue the value is exactly true (checkboxes) { required: true }
min(n) / max(n) a number is at least / at most n { min: { min, actual } }
minLength(n) / maxLength(n) the text or array length is within the limit { minlength: { requiredLength, actualLength } }
pattern(re) the whole value matches the regular expression { pattern: { requiredPattern, actualValue } }
email the value looks like an email address { email: true }

Three details save hours of confusion:

  1. Only required complains about an empty value. minLength, pattern, email and the others treat an empty control as valid, so that an optional field is not marked wrong just because it is blank. Combine them with required when the field is mandatory.
  2. The error key for minLength is the lowercase minlength (and maxlength). The method is camel case; the key is not.
  3. Validators.email is deliberately loose. It catches obvious typos, not every invalid address. Real verification means sending a message.

When you have a list but need a single function, Validators.compose([a, b]) merges them; Angular does this for you when you pass an array.

Reading errors in the template

A control exposes errors, plus helpers hasError('minlength') and getError('minlength'). Show a message only after the user has had a chance to type, which usually means checking touched (or dirty):

HTML
<label for="name">Name</label>
<input id="name" formControlName="name" [attr.aria-invalid]="name.invalid && name.touched" />

@if (name.touched && name.invalid) {
  <p class="error" role="alert">
    @if (name.hasError('required')) {
      Please enter your name.
    } @else if (name.hasError('minlength')) {
      Use at least {{ name.getError('minlength').requiredLength }} characters.
    }
  </p>
}

Putting every message in the template gets repetitive. A common refinement is a small function (or pipe) that maps an errors object to text, so the template says {{ errors | errorText }}. The stand-in later in this lesson uses exactly that idea.

Writing a custom synchronous validator

Because a validator is only a function, a custom one is a function with the right shape. If it needs configuration, write a function that returns the validator (a "validator factory"), just like Validators.minLength(2) does:

TypeScript
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export function forbiddenNames(names: string[]): ValidatorFn {
  const blocked = names.map((n) => n.toLowerCase());
  return (control: AbstractControl): ValidationErrors | null => {
    const value = String(control.value ?? '').toLowerCase();
    return blocked.includes(value) ? { forbiddenName: { value } } : null;
  };
}

export const noWhitespace: ValidatorFn = (control) =>
  /\s/.test(String(control.value ?? '')) ? { whitespace: true } : null;

Use them like any other: username: ['', [Validators.required, noWhitespace, forbiddenNames(['admin', 'root'])]]. Name the error key after the rule, make it a readable noun or phrase, and put useful details in the value ({ forbiddenName: { value } }) so that the message can quote them. Remember the empty-value convention: return null for an empty value unless your validator is itself a "required" rule.

The first runnable example builds this small toolbox from scratch and composes it.

TypeScript Stand-in: validator functions and composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the second line of the output: the empty string fails only required, because minLength and pattern ignore empty values. And 'ada lovelace' fails two rules at once, so errors is a merge, which is why you can show all the problems or just the first.

Validating several fields: group validators

A validator on a single control cannot see its siblings. For rules that involve more than one field (password and confirmation, start date before end date, "at least one phone or email"), put the validator on the parent group. It receives the group as its control argument, so it can read control.get('password') and control.get('confirm'):

TypeScript
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const passwordsMatch: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
  const password = group.get('password')?.value;
  const confirm = group.get('confirm')?.value;
  return password === confirm ? null : { passwordMismatch: true };
};

readonly form = this.fb.nonNullable.group(
  {
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirm: ['', Validators.required],
  },
  { validators: passwordsMatch },
);

The error lands on the group, not on confirm. So the template checks form.hasError('passwordMismatch'), and the form's invalid becomes true as soon as either a child or the group has an error. Two more points:

  • The group validator runs whenever any child value changes, so it must handle half-filled forms without throwing (note the ?.).
  • If you prefer to show the error under the confirm field, either read the group's error there or have the validator call confirm.setErrors({ mismatch: true }) on the child. The first option is simpler and keeps validators free of side effects.

Async validators

Some rules need a server: is this username free, does that coupon exist? An async validator returns a Promise or an Observable, which must produce null or an error object and complete. Pass it as the third argument or in the asyncValidators option.

TypeScript
import { AsyncValidatorFn } from '@angular/forms';
import { catchError, map, of, switchMap, timer } from 'rxjs';

export function usernameAvailable(api: UsersApi): AsyncValidatorFn {
  return (control) =>
    timer(300).pipe(                                   // debounce: wait for a pause in typing
      switchMap(() => api.exists(control.value)),      // ask the server
      map((exists) => (exists ? { usernameTaken: true } : null)),
      catchError(() => of(null)),                      // never block the user on a network error
    );
}

username: ['', [Validators.required], [usernameAvailable(this.api)]],

Three rules govern async validators, and all three are about order and timing:

  1. They run only after every sync validator passes. Asking the server whether '' or 'a' is taken would be a waste, so Angular skips the async step while sync errors exist.
  2. While they run, the control's status is 'PENDING', and so is its parent's. A submit button should wait for form.pending to end; checking only invalid is a classic bug.
  3. When the value changes again, Angular unsubscribes from the previous async validation and starts a new one. That is why the timer(300).pipe(switchMap(...)) trick works as a debounce: a quicker keystroke cancels the timer before the request is sent, and a slow, stale answer can never overwrite a newer one.
flowchart TD
  V["Value changes"] --> S["Run sync validators"]
  S -->|"errors found"| I["status: INVALID<br/>async validators skipped"]
  S -->|"no errors"| P["status: PENDING<br/>run async validators"]
  P -->|"result null"| OK["status: VALID"]
  P -->|"error object"| I2["status: INVALID"]
  P -->|"value changes again"| C["Previous validation cancelled"] --> S

Sync validators gate the async ones; a newer value cancels a pending async check.

When does validation run? updateOn

By default every keystroke updates the control's value and runs the validators, so an error can flash up while the user is still typing the first character. The updateOn option moves that moment:

  • 'change' (the default): on every input event.
  • 'blur': when the field loses focus.
  • 'submit': when the form is submitted.
TypeScript
username: this.fb.nonNullable.control('', {
  validators: [Validators.required, Validators.minLength(3)],
  asyncValidators: [usernameAvailable(this.api)],
  updateOn: 'blur',
}),

You can also set it for a whole group, this.fb.nonNullable.group({...}, { updateOn: 'submit' }); children inherit it unless they set their own. With blur or submit, the control's value does not change until that moment, which also means valueChanges stays quiet. That is exactly what you want for an expensive async check, and exactly what surprises people who expected a live preview.

The second stand-in is a tiny control that implements the three behaviors above: sync-before-async ordering, the PENDING status, discarding stale async answers, and updateOn: 'blur'.

TypeScript Stand-in: async validation, PENDING and updateOn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice the first block: "ab" is rejected by minlength and the server is never contacted (zero calls). Then "ada" goes to PENDING, and only the answer changes the status. In the quick-retype step the slow "ada" response comes back after "linus" is already settled, and the control discards it. Finally, the blur-mode control stays untouched while the user types: its value, status and errors only change when blur() runs.

Dynamic validators and good habits

Validators can change after creation. control.setValidators([...]) replaces them, addValidators and removeValidators adjust the list, and you must call control.updateValueAndValidity() afterwards so that the new rules run. This is handy for fields that become required only when another answer says so.

A few habits keep forms pleasant:

  • Validate on the client for convenience and on the server for safety. Anyone can bypass your Angular code.
  • Show errors after touched or dirty, not on first render, and pair the message with aria-invalid and role="alert" so assistive technology announces it.
  • Keep validators pure: no reading from services at call time, no mutation of the control. Create them with their dependencies already captured, as usernameAvailable(api) does.
  • Do not turn a network failure into "username taken". Decide explicitly what a failed check means (above, it passes and the server rechecks on submit).
  • Disabled controls are not validated, which is how you switch a rule off entirely.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a synchronous validator function return when the control is valid?

    A validator returns null for valid, or an object whose keys name the failed rules. The control is invalid whenever the merged errors object is not empty.
  2. 2. A control has Validators.minLength(5) and the user leaves it empty. What happens?

    Validators other than required treat an empty value as valid so that optional fields are not flagged. Add Validators.required for mandatory fields.
  3. 3. Where does the error from a group-level passwordsMatch validator appear?

    A validator reports on the control it is attached to, so a group validator's errors belong to the group. The template reads them from the group.
  4. 4. When do async validators run?

    Angular skips async validators while sync errors exist, and sets the status to PENDING while an async check is running. A new value cancels the previous async validation.
  5. 5. What does updateOn 'blur' change?

    With 'blur' (or 'submit') the control model is updated at that moment, so valueChanges and validation also wait until then.

Summary

  • A validator is a function from a control to null (valid) or an errors object (invalid); Validators provides required, requiredTrue, min, max, minLength, maxLength, pattern and email.
  • Only required flags an empty value, and the length error key is lowercase minlength.
  • Write custom validators as functions, or as factories that return a function when they need configuration.
  • Put rules that involve several fields on the parent group; their errors belong to the group.
  • Async validators return a Promise or Observable that completes, run only after sync validators pass, set PENDING, and are cancelled by newer values.
  • updateOn (change, blur, submit) decides when the value and validation update.
  • The Angular snippets are read-only; the validator toolbox and the async control are stand-ins.

Next: Signal Forms