Angular › Forms

How do you add validation to a reactive form field, and how do you show an error message to the user?

Intermediate

Answer

You pass one or more validator functions, like Validators.required, when creating a FormControl, and check the control's valid and touched properties in your template to decide whether to show a specific error message.
form = new FormGroup({
  email: new FormControl('', [Validators.required, Validators.email])
});

<input [formControl]="form.controls.email" />
@if (form.controls.email.invalid && form.controls.email.touched) {
  <p>Please enter a valid email address</p>
}
Real-world example A signup form shows a clear error message right below the email field the moment a user tabs away from an invalid entry, using Angular's built in validators combined with the control's touched and invalid state.

Common follow-ups: What is the difference between the touched and dirty properties on a form control?;How would you create your own custom validator function for a rule Angular does not provide built in?