Skip to main content

What is a validator in Angular?

A validator in Angular is a function that checks the value of a form field and returns the result of the check.

If the value is correct: null is returned. If there is an error: an object with a description is returned, for example:

typescript
{ required: true } or { minlength: { requiredLength: 5, actualLength: 3 } }

There are two types:

  • Synchronous validators - run immediately (Validators.required, Validators.email, Validators.minLength, and so on).
  • Asynchronous validators - run with a delay (for example, a request to the server to check a username).

Example:

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

Validators help Angular automatically determine the valid / invalid state and show errors to the user.

Short Answer

Interview ready
Premium

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