Angular Reactive Forms Validation

In this article, will explore how angular reactive forms validation works. One of the common tasks that is performed, while building a form is Validation. We will show you how to build Reactive Forms and apply Built-in validators. In the next tutorial, you will learn how to create custom validators in Reactive Forms.

We looked at how the validation works in the Template-driven Forms tutorial. Most of the concepts explained in that tutorial are equally applicable here.

Validators in Reactive Forms

What is a Validator

A Validator is a function that checks the instance of FormControlFormGroup or a FormArray and returns a list of errors. If the Validator returns a null means that validation has passed

How to add a Validator to Reactive Forms

We configure the validators as the second and third argument to the FormControl, FormGroup or FormArray in the component class. The second argument is a collection of sync validators and the third argument is a collection of an async validators.

sync validators runs validations and returns immediately. They either return a list of errors or null if no errors found.

async validators: returns a Promise or Observable. They either return a list of errors or null if no errors are found.

Built-in Validators

The Angular ReactiveForms Module provides several Built-in validators out of the box. They are required, minlength, maxlength & pattern etc.

Reactive Forms Validation Example

W learned how to create Angular Reactive Forms in the previous tutorial. We will now add some of the built-in validators to that example.

Model

Here is the contactForm model from the previous tutorial.

Disabling the Browser validation

First, we need to disable browser validator by adding the novalidate attribute to the <form> element as shown below. If this attribute is present then the form is not validated by the built-in HTML5 validation when submitted.

Adding in Built-in Validators

The mentioned earlier, the Angular has provided several built-in validators out of the box.

Required Validator

The required validator is a sync validator, which returns true only if the formcontrol has a non-empty value entered. The second argument of the FormControl takes the Sync Validator.

Minlength Validator

Minlength validator requires the control value must not have less number of characters than the value specified in the validator.

For Example, minlength validator ensures that the firstname value has at least 10 characters.

Maxlength Validator

This Validator requires that the number of characters must not exceed the value specified in the validator.

Pattern Validator

This Validator requires that the control value must match the regex pattern provided in the attribute. For example, the pattern ^[a-zA-Z]+$ ensures that the only letters are allowed (even spaces are not allowed). Let us apply this pattern to the lastName

Email Validator

This Validator requires that the control value must be a valid email address. We apply this to the email field

After adding all the validators, our final contactForm will look like this.

Disable Submit button

We have successfully added the validators. Now, we need to disable the submit button if our form is not valid.

The Angular Forms API exposes the state of the forms through the FormGroup, FormControl & FormArray instances. The FormGroup control has a property valid, which is set to true if all of its child controls are valid.

The contactForm represents the top-level FormGroup. We use it to set the disabled attribute of the submit button.

Displaying the Validation/Error messages

We need to provide a short and meaningful error message to the user. We do that by using the error object returned by the FormControl instance

Every form element has a FormControl instance associated with it. It exposes the state of form element like valid, dirty, touched etc.

There are two ways in which you can get the reference to the FormControl.

One way is to use the contactForm variable. We can use contactForm.controls.firstname.valid to find out if the firstname is valid.

The other way to is to define getter function for each FormControl instance in the component class.

and then use it in the template as follows

Dirty & touched

Apart from checking valid we are also checking for the dirty & touched. Because we do not want the application to display the error when the form is displayed for the first time. We want to display errors only after the user has attempted to change the value. The dirty & touched properties help us do that.

dirty: A control is dirty if the user has changed the value in the UI.
touched: A control is touched if the user has triggered a blur event on it.

Error message

The error message “First Name is not valid ” is not helpful. The firstname has two validators. required and minlength

Any errors generated by the failing validation is updated in the errors object. The errors object returns the error object or null if there are no errors.

Final Code

app.component.ts

app.component.html

Summary

We just learned how Angular Reactive Forms Validation works.

List of All Articles on Angular Forms

  1. Angular Forms Tutorial: Fundamental & Concepts
  2. Template Driven Forms in Angular
  3. Set Value in Template Driven forms in Angular
  4. Reactive Forms in Angular
  5. FormBuilder in Reactive Forms
  6. SetValue & PatchValue in Angular
  7. StatusChanges in Angular Forms
  8. ValueChanges in Angular Forms
  9. FormControl
  10. FormGroup
  11. FormArray Example
  12. Build Dynamic or Nested Forms using FormArray
  13. Validations in Reactive Forms in Angular
  14. Custom Validator in Reactive Forms
  15. Passing Parameter to Custom Validator in Reactive Forms
  16. Inject Service into Custom Validator
  17. Validation in Template Driven Forms
  18. Custom Validator in Template Driven Forms

7 thoughts on “Angular Reactive Forms Validation”

  1. Thank you! It is very useful.
    I assume that the author wrote this text in an old version of Angular. I googled a few syntax errors and fixed them. VS code itself helps.

  2. AMAN KUMAR SINGH

    Thanks Team,
    your code really helped me a lot.
    But there is an issue in your code while fetching data and checking it for error. after error there should be question mark as you are fetching the error. It didn’t worked in angular 12. No idea about previous versions.

    “” it should be like this for angular 12———– “”

    1. it’s not working for me as well can you please tell me how can I solve the error?

      I’m getting this error {Object is possibly ‘null’.ngtsc(2531)}

      for this {errors.required}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top