Built-In Validators

required, minLength, email, pattern — Pre-Built

Built-In Validators

The Validators class ships the common validators you compose into form controls — required, minLength, maxLength, email, pattern, and more.

4 min read Level 2/5 #angular#forms#validation
What you'll learn
  • Apply Validators.required and friends
  • Compose multiple validators
  • Read errors per field

You rarely need custom validators for common rules. Angular’s Validators class covers most of them.

The Bundled Set

  • Validators.required
  • Validators.requiredTrue — for checkboxes that must be checked
  • Validators.email
  • Validators.min(n) / Validators.max(n) — numeric ranges
  • Validators.minLength(n) / Validators.maxLength(n) — string length
  • Validators.pattern(regex)
  • Validators.nullValidator — no-op (rarely needed)

Applying Them

A single validator is passed directly; multiple validators go in an array.

import { FormControl, Validators } from '@angular/forms';

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

const password = new FormControl('', [
  Validators.required,
  Validators.minLength(8),
  Validators.pattern(/(?=.*\d)(?=.*[A-Z])/),
]);

Reading Errors

control.errors is an object keyed by validator name, or null if valid.

@let emailCtrl = form.controls.email;

<input formControlName="email" />

@if (emailCtrl.touched && emailCtrl.errors) {
  @if (emailCtrl.errors['required']) {
    <p>Email is required.</p>
  } @else if (emailCtrl.errors['email']) {
    <p>That email looks wrong.</p>
  }
}

The touched check delays errors until the user has interacted with the field — better UX than yelling on page load.

Cross-Field Validation

You can also put validators on a FormGroup to check across fields. That is what custom validators are for — covered next.

Custom Validators →