AI Hints
Home›Angular Tutorial›FormGroup, Validators and Showing Errors
Angular · Lesson 86 of 120

Validators

Rules for fields.

⏱ 2 min read▶ Video at 1:42:59🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Users make mistakes. An empty email, or ninety nine copies of one book. Validators are rules, that each field must follow.

  • Users make mistakes
  • Fields need rules
  • Validators

Built-in validators

Required means the field can't be empty. Email checks the shape of an email address. Min, and max, limit numbers. Min length, and max length, limit text. And pattern checks text against a regular expression.

ValidatorRule
Validators.requirednot empty
Validators.emaillooks like an email
Validators.min(1) / max(5)number limits
Validators.minLength(8)text length
Validators.pattern(/.../)matches a pattern

Rules and errors

Each control gets a list of validators, after its starting value. The status line shows whether the email is valid. And errors shows each control's broken rules, as JSON. We type sam at, and nine copies. Run it. The email is invalid. It has an email error. And copies has a max error, with the limit, and the actual value.

app.tstypescript
import { Component } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { ReactiveFormsModule, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule, JsonPipe],
  template: `
    <input [formControl]="email" placeholder="Email">
    <input [formControl]="copies" type="number">
    <p>Email status: {{ email.status }}</p>
    <p>Email errors: {{ email.errors | json }}</p>
    <p>Copies errors: {{ copies.errors | json }}</p>
  `,
})
export class App {
  email = new FormControl('', [Validators.required, Validators.email]);
  copies = new FormControl(1, [Validators.min(1), Validators.max(5)]);
}
Also uses actions.json
[{"type": "input", "text": "sam@"}, {"clear": "input[type=number]"}, {"type": "input[type=number]", "text": "9"}]

Summary

Validators are rules on each control. Errors lists what's broken, and the status says if the form is valid. Next, showing friendly error messages.

Key takeaways
  • Validators.required
  • Validators.max(5)
  • control.errors
Next up: Showing Errors — friendly messages