Validation

In this lesson, we'll learn how to validate input.

We'll cover the following

Validation is necessary for almost any form. We can use reactive forms to perform validation on the client side, which saves users from having to wait for a response from the server. They’ll be able to receive immediate feedback.

We’ll want to ensure every input in the form contains valid values for a credit card. Angular comes with validators out of the box. Validators are functions that check a value against some rules. A boolean value is returned based on whether the input’s value passes the validators rules.

Importing validators

We can use validators in our project by importing them from the @angular/forms package. We’ll update the import statement in the app.component.ts file.

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

We’re importing the Validators class because reactive forms are configured in the class. If we want to add validators to the inputs, we’ll need to add them to their controllers.

Using a validator

We’ll have access to a couple of built-in validators defined by Angular. A full list can be found here.

The second argument of the constructor function for the FormControl class is an array of validators. We’ll use two validators: required and minLength. In the class, we’ll update the form control for the name input.

Get hands-on with 1200+ tech skills courses.