Angular Reactive Form Validation

Getting started with Angular Reactive Form Validation


Handling user input with forms is the cornerstone of many common applications.

Applications use forms to enable users to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks.

We will be looking at how Angular handles form Validation in Reactive Form.

Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

Reactive and template-driven forms process and manage form data differently. Each offers different advantages.

Our main focus is Reactive Form:

Reactive forms provide a model-driven approach to handling form inputs whose values change over time.  It shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values. –Angular.io

We are going to create a simple user registration form. 

Prerequisites

Navigate to the folder where you want to create your project file. Open a command window and run the command shown below.

ng new angular-forms-validation --routing=false --style=scss

The command above creates a new Angular application. The option to create the routing module is set to false and style files extension is set to scss.

Navigate to the new project folder and run the command to install bootstrap:

cd angular-forms-validation
npm Install bootstrap --save

Add the following import definition in styles.scss file.

@import "~bootstrap/dist/css/bootstrap.css";

Importing ReactiveFormsModule API

In order to work with Reactive Forms in Angular, we must import ReactiveFormsModule  API in the app module file. app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ],
})
export class AppModule { }

Use of FormGroup, ngSubmit and formControlName in an Angular Template

There is some set of component classes that communicates with Reactive forms to manage the form data. Below is a list of some of them that we will be looking out in this project:

FormGroupFormGroup is a top-level API that maintains the values, properties and validation state of a group of AbstractControl instances in Angular.
FormBuilderIt provides helpful methods to create control instances in Angular Reactive Forms.
ngSubmitThis event is called when the form is submitted.
FormControlIt communicates with an HTML Form element like input or select tag, this API handles the individual form value and validation state.

Required field validation

Let’s look out how to handle validation on each of the form field listed above. In our project folder open app.component.html and write the code below.

<form [formGroup]="registrationForm" (ngSubmit)="submitRegistrationForm()">
</form>

We started by creating our form and we binded formGroup and ngSubmit class to it in order to tracks the value and validity state of a group of FormControl instances and to submit the value when the user is done and hits the submit button.

<input style="width: 100%;" type="text" formControlName="FullName" placeholder="" name="FullName" autocomplete="off" [ngClass]="{ 'is-invalid': submitted && registrationForm.controls.FullName.errors }" />

<div *ngIf="submitted && registrationForm.controls.FullName.errors" class="text-danger">
    <div *ngIf="registrationForm.controls.FullName.errors.required">
    FullName is required
    </div>
</div>

<div class="text-center box">
  <button>
       Create
   <div *ngIf="loading" class="spinner-border" role="status">
       <span class="sr-only">Loading...</span>
    </div>
  </button>
</div>

We have created our input tag and we bind formControlName to the input to get the value when a user types. And is-invalid that we bind to our div will automatically determine if an input is good based on the rules placed on it and show an error if the user makes a mistake.

Radio Buttons in Reactive Forms

Let’s look at how we can work with Radio Buttons in our registration form.

To work with Radio Buttons in Angular application, we must set dynamic values in the form control array.

Since the user can select any values we should use setValue() method to assign the dynamic values to form control array. Open app.component.html and write the below code.

<!-- Radio Buttons -->
<div class="custom-control custom-radio">
  <input id="male" type="radio" class="custom-control-input" name="gender"     formControlName="gender" value="male" checked>
      <label class="custom-control-label" for="male">Male</label>
</div>

<div class="custom-control custom-radio">
   <input id="female" type="radio" class="custom-control-input" name="gender" formControlName="gender" value="female">
     <label class="custom-control-label" for="female">Female</label>
</div>

In the above code, we created our radio buttons and added some default value to it but we are looking at how to set the selected value of Radio Buttons using Angular Reactive Forms.

registrationForm = this.fb.group({
  gender: ['male']
})

To select the value from the radio button we Passed the radio button value name within the form control array. 

Using FormBuilder API

The FormBuilder service offers 3 useful methods: group(), control(), and array(). These methods generate instances in our component classes including form controls, form groups, and form arrays. Let’s look at how FormBuilder works. Open app.component.ts and write the code below.


import { Component } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  title = "angular-forms-validation";

  registrationForm: FormGroup;
  invalidlogin: boolean = false;
  submitted = false;
  loading = false;
  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.registrationForm = this.formBuilder.group({
      FullName: ["", Validators.required],
      phone: ["", Validators.required],
      email: ["", [Validators.required, Validators.email]],
      password: ["", [Validators.required, Validators.minLength(6)]]
    });
  }

  submitRegistrationForm() {
    this.submitted = true;
    this.loading = false;
    if (this.registrationForm.invalid) {
      return console.log('Account created successfully');
    }
    this.loading = true;
  }

}

We start by importing FormBuilder, FromGroup, and Validator that we used to track our form.

Then we declared registrationForm variable and assigned the value as FormGroup.

We also called this.registrationForm and passed the Value to FormBulider that will check if the values from our Form has passed the necessary requirement assign to it or not and if passed the Requirement, it will send the value to where ever we want it to but in this project, we console.log the value and if not passed, it will throw an error to the user telling them where they have made a mistake for the user to correct.

Conclusion

In this tutorial, we were able to create a registration form that we used to learn and understand how reactive form validation works in Angular.

Get the source code from GitHub and play around for a better understanding.


Share on social media

//