Skip to main content

What types of validators are there?

Angular has two types of validators:

Synchronous validators

  • Checked immediately, without waiting.
  • Used most often.
  • Examples of built-in ones:
    • Validators.required - the field must not be empty;
    • Validators.email - checks that the e-mail is correctly formatted;
    • Validators.minLength(n) / Validators.maxLength(n) - limit the length;
    • Validators.pattern(regex) - checks against a regular expression.
    • You can write your own, returning null (if all is fine) or an error object.

Asynchronous validators

  • Used when the check takes time, for example a request to the server.

  • Return a Promise or Observable.

  • Example: checking whether a username is already taken:

    typescript
    checkUsername(control: FormControl) { return this.api.checkUser(control.value).pipe( map(isTaken => (isTaken ? { usernameTaken: true } : null)) ); }

Both types can be applied to individual FormControl instances as well as to entire FormGroup instances.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.