Angular 7 Reactive – Form Validation Simple Example
Angular JS 06-Feb-2021

Angular 7 Reactive – Form Validation Simple Example

Every application needs the user input and the input should be correct it is the developer’s responsibility. Angular 7 comes with the form validation feature.

Today we will learn about the Angular 7 form validation.

So let’s get started with the simple registration form validation. We need a Angular 7 project. If you don’t know how to create Angular 7 project. Follow this tutorial.

Register Reactive Forms Module

We will use ReactiveFormsModule. We need to register our ReactiveFormsModule in the AppModule. To include it open the ‘app.module.ts’ file and put the below code at the top of the file

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

Then Include it in the imports array of the @NgModule. So our module wil looks like this.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
 
import { AppComponent } from './app.component';
 
@NgModule({
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [AppComponent]
})
 
export class AppModule { }

Import form component

Open app.component.ts file and import the form component. To include it put the below code at the start of the file

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

 

Declare the variable

We will declare the variable that will store all the form property on it. This will be type of the FormGroup.

registerForm: FormGroup;
submitted = false;

Create FormBuilder instance

Now we will create instance of the FormBuilder. Put the below code

constructor(private formBuilder: FormBuilder) { }

 

Declare field and validation rules

Now we will create instance of the Angular 7 formBuilder. Declare all the form field available in the form and set their validation rules. Put the below code under the ngOnInit() method.

this.registerForm = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(6)]]
});

Create method to handle the form submit

Now we will create a method which will binds the form submit event.

Open the file and put the below code

onSubmit() {
    this.submitted = true;
 
    // stop the process here if form is invalid
    if (this.registerForm.invalid) {
        return;
    }
 
    alert('SUCCESS!!');
}

After completing all the above step. Our component will looks like this

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 
@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})
 
export class AppComponent implements OnInit {
    registerForm: FormGroup;
    submitted = false;
 
    constructor(private formBuilder: FormBuilder) { }
 
    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            password: ['', [Validators.required, Validators.minLength(6)]]
        });
    }
 
    onSubmit() {
        this.submitted = true;
 
        // stop the process here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }
 
        alert('SUCCESS!!');
    }
}

Create template

We will create html markup for displaying the form in the browser. Open the app.component.html file and put the below html on it

<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Register</h3>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.firstName.errors }" />
<div *ngIf="submitted &amp;&amp; registerForm.controls.firstName.errors" class="text-danger">
<div *ngIf="registerForm.controls.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.lastName.errors }" />
<div *ngIf="submitted &amp;&amp; registerForm.controls.lastName.errors" class="text-danger">
<div *ngIf="registerForm.controls.lastName.errors.required">Last Name is required</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.email.errors }" />
<div *ngIf="submitted &amp;&amp; registerForm.controls.email.errors" class="text-danger">
<div *ngIf="registerForm.controls.email.errors.required">Email is required</div>
<div *ngIf="registerForm.controls.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted &amp;&amp; registerForm.controls.password.errors }"  />
<div *ngIf="submitted &amp;&amp; registerForm.controls.password.errors" class="text-danger">
<div *ngIf="registerForm.controls.password.errors.required">Password is required</div>
<div *ngIf="registerForm.controls.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
</div>

Angular 7 form validation form will looks like this