Angular
Intro to Reactive Forms in Angular - Validate Forms
  •  

Demo: Built-in Validators

PRO

Let’s start off this section by talking about built-in validators. Angular provides us with quite a few validators that you can see here in the API reference. A validator is a function that either returns null (which means no errors) or an error map that tells us what makes it invalid. A lot of the time when I’ve created forms, I’ve been able to get by with just built-in validators. There may be a couple special cases where you’ll need to create custom validators but we’ll first talk about the built-in ones. Some built-in validators help us to make a field required, check if the field is formatted like an email, match a certain pattern, and more.

In this demo, I want first name, last name, and email controls to be required. I also want to make sure the email is formatted like a common email, and that the last "I promise" checkbox is checked before they can submit. All these need to be true for the form to considered valid. I’m also showing the form’s validity status so we can see it update live.

In a reactive form, our validation logic is done in the component, so starting there, the first thing we need to do is import Validators from @angular/forms. Then in initializeForm(), we’ve so far been keeping it simple by initializing a form control’s value just to a string. When we want to add Validators, we’ll update this to an array where the first argument is the initial control value and the second argument is the synchronous Validator(s). We'll add the built-in validators of required, email, and requiredTrue for the promise checkbox. For email, it needs multiple Validators so we'll it to an array containing: [Validators.required, Validators.email]

Lastly, we'll add getters to allow us to access the form controls with shorthand. For example: get email(): FormControl { return this.regForm.get('email') as FormControl; }