Angular 14 Reactive Forms Validation Tutorial with Example

Angular Reactive Forms validation tutorial, this step by step guide explains validation in angular reactive forms. You will learn to create a basic sign-up form and understand how to implement validation in angular forms immaculately.

Reactive forms offer a model-driven approach for managing form inputs whose values transform over and over again.

Throughout this comprehensive tutorial, you will find out how to build or create a basic form, progress to using multiple controls in a group, and validate form input fields using reactive forms APIs.

FormGroup: Tracks the value and validity state of a group of FormControl instances.

FormControl: Tracks the value and validation status of an individual form control.

FormBuilder: Creates an AbstractControl from a user-specified configuration.

AbstractControl: This is the base class for FormControl, FormGroup, and FormArray.

FormArray: Tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances.

Angular 14 Reactive Forms Validation Example

You have to assimilate the following guide to create and validate reactive forms in angular application.

  • Create Angular Project
  • Install Bootstrap Package
  • Import ReactiveFormsModule in App Module
  • Create Form Component
  • Update the Main App Component
  • Test Angular Form Validation App

Create Angular Project

Before starting this tutorial, first, make sure you have installed the Angular CLI globally on your device:

npm install -g @angular/cli

After that, you need to invoke the installation of a new angular project:

ng new ng-form-validaiton

Make sure to move to the project root:

cd ng-form-validaiton

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Install Bootstrap Package

Make sure to install Bootstrap library in angular for creating immaculate forms; consequently, it helps you create sleek, intuitive and robust front-end in exorbitantly low time.

npm i bootstrap

Add Bootstrap library CSS path in angular.json file:

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
         ]

Add Reactive Forms Module

For using the reactive form controls, must register ReactiveFormsModule likewise FormsModule from the @angular/forms package and insert inside the NgModule’s imports array.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Create Form Component

In this step, you have to generate a new component using the following command:

ng g c reactive-form

Open reactive-form.component.ts file, in the same way update the below code:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-reactive-form',
  templateUrl: './reactive-form.component.html',
  styleUrls: ['./reactive-form.component.css']
})

export class ReactiveFormComponent implements OnInit {

  userForm: FormGroup;

  constructor(public formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.userForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(4)]],
      email: ['', [Validators.required]],
      phone: ['', [Validators.required]],
      message: ['', [Validators.required]]
    })  
  }
  
  get getControl(){
    return this.userForm.controls;
  }
  
  onSubmit(){
    console.log(this.userForm);
  }

}

To create and validate form import FormGroup, FormBuilder and Validators modules from “@angular/forms” package.

Insert FormBuilder in the constructor, also evoke the form object using FormGroup class.

Inside the ngOnInit lifecycle hook, declare the form inside the group method. Even more add a name, email, phone and message form controls respectively and gradually.

To implement validation in angular form inputs inject the Validators class, It offers a couple of ready-made validators which can be addressed by form controls instances.

Lastly, to shorten up the process of accessing the form control instances use the getter method.

Open reactive-form.component.html file, on top of that insert the below code:

<h2 class="mb-5 text-center">Angular Form Validation Example</h2>

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate>

  <div class="form-group">
    <label>Name</label>
    <input type="text" class="form-control" formControlName="name">
    <div *ngIf="getControl.name.touched && getControl.name.invalid" class="text-danger">
      <div *ngIf="getControl.name.errors.required">Name is required.</div>
      <div *ngIf="getControl.name.errors?.minlength">Minimum 4 character are required.</div>
    </div>
  </div>

  <div class="form-group">
    <label>Email</label>
    <input type="text" class="form-control" formControlName="email">
    <div *ngIf="getControl.email.touched && getControl.email.invalid" class="text-danger">
      <div *ngIf="getControl.email.errors.required">Email is required.</div>
      <div *ngIf="getControl.email.errors.email">Email seems invalid.</div>
    </div>
  </div>

  <div class="form-group">
    <label>Phone</label>
    <input type="text" class="form-control" formControlName="phone">
    <div *ngIf="getControl.phone.touched && getControl.phone.invalid" class="text-danger">
      <div *ngIf="getControl.phone.errors.required">Phone is required.</div>
    </div>
  </div>

  <div class="form-group">
    <label>Message</label>
    <textarea type="text" class="form-control" formControlName="message"></textarea>
    <div *ngIf="getControl.message.touched && getControl.message.invalid" class="text-danger">
      <div *ngIf="getControl.message.errors.required">Message is required.</div>
    </div>
  </div>
  <button class="btn btn-danger btn-block" type="submit">Submit</button>
</form>

Create form object using formGoup directive, additionally define the submit event with novalidate property.

Make the form inputs ready by adding formControlName property, and the form control will contain the form input value.

As you can see, we access the form errors, and touched props and added the form validation for required, minimum characters and touched.

Update the Main App Component

Copy Component selector from ReactiveFormComponent file and declare within the app component file, so open app.component.html file, in the second place add the following code:

<div class="container mt-5" style="max-width: 550px;">
  <app-reactive-form></app-reactive-form>
</div>

Test Angular Form Validation App

Eventually, we have completed all the steps to build the angular reactive form; now, we have to test the application.

ng serve

Open browser, enter the below url:

http://localhost:4200

Angular Validation Example with Reactive Forms

Conclusion

Ultimately, this tutorial is over. Using this profound guide, now you can create an angular form with reactive forms and validate using reactive forms validator API.

I reckon you would love this tutorial and propel forward to other developer friends.