Lesson 19 / 32

Form Validation

Enforce rules with built-in validators and show error messages only after users touch a field.

Built-in validators

Pass validator functions when creating a FormControl — Validators.required, Validators.email, Validators.minLength, and more.

form = new FormGroup({
  email: new FormControl('', [Validators.required, Validators.email]),
  password: new FormControl('', [Validators.required, Validators.minLength(8)]),
});

Showing errors

Check a control's invalid and touched state to show an error only after the user has interacted with the field.

<input formControlName="email">
@if (form.controls.email.invalid && form.controls.email.touched) {
  <small>Enter a valid email.</small>
}

Quick check: Where do you attach validators to a reactive form control?

  • As an attribute in the HTML template
  • Inside the component's constructor only
  • As the second argument when creating the FormControl
  • In the CSS file
Answer

As the second argument when creating the FormControl — `new FormControl('', [Validators.required])` passes validators directly to the control.