Skip to main content

Handle Form Validation in Angular 7

Forms are an important of web applications. The Forms are used to take user’s input data like user registration form to save user data or user login form.

Angular 7 is a feature rich language that allow to create user friendly forms with validations. There are two kinds of forms like template driven forms and reactive forms
are created in Angular 7.

In our previous tutorial, we have explained how to create Angular 7 Forms. So here in this tutorial you learn how to create Angular 7 form validation with both type of forms.

We will cover this tutorial step by step with example to create both type of Angular 7 Forms (template driven forms and reactive forms) with Validations.

Also, read:

1. Template Driven Angular 7 Form Validation

Here we will add the validations to the template driven form. We will use the same input validation attribute as we use with the native HTML Form Input validation. The Angular use the directives to match the input attribute with the validator function to validate it. Whenever form input values changes, it runs the validation and generate validation errors. So let’s implement this step by step.

Step1: Create Angular 7 Project

First we will install the Angular 7 to create the new Angular project. We will create ng7formvalidation project.

ng new ng7formvalidation

Now, go inside the ng7formvalidation folder and open the folder.

cd ng7formvalidation

Step2: Install Bootstrap 4 CSS Framework

We will install the Bootstrap 4 CSS Framework using the below command.

npm install bootstrap --save

After Bootstrap install, we will include the bootstrap 4 inside the angular.json file inside styles array.

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

Step3: Add FormsModule

We will add the FormsModule module inside app.module.ts file.

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

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We will add the below code to the app.component.ts file. We will send the form data when the form will be submitted.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data: any = {};

  onSubmit() {
    console.log(JSON.stringify(this.data));
  }
}

Step4: Create Form and Add Validation in Template

Now finally in app.component.ts file, we will add the FORM HTML with input and its attributes to implement form with validations. Here will validate a input for blank value, length and forbidden values.

<div class="container">
  <h2>Angular 7 Template Driven Form Validation</h2>
  <form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
    <div class="form-group">
      <input id="empName" name="empName" class="form-control"
      required minlength="5" appForbiddenName="xyz"
      [(ngModel)]="data.empName" #empName="ngModel"/>
    </div>
    <div class="form-group">
      <div *ngIf="empName.invalid && (empName.dirty || empName.touched)"
          class="alert alert-danger">
        <div *ngIf="empName.errors.required">
          Employee name is required.
        </div>
        <div *ngIf="empName.errors.minlength">
          Employee name must be at least 5 characters long.
        </div>
        <div *ngIf="empName.errors.forbiddenName">
          Employee name cannot be xyz.
        </div>
      </div>
    </div>
    <div class="form-group">
      <button class="btn btn-primary" [disabled]="f.form.pristine || f.form.invalid">Save</button>
    </div>
  </form>
</div>

Now save the code and go to the browser and see the form with validation result.

2. Angular 7 Reactive Form Validation

The Reactive forms is a technique to create form in Angular 7. The reactive forms enables the reactive style of forms management to manage data flow between non-UI data model and a UI-oriented form model to control the HTML form controls. It enables us to use the reactive programming patterns, testing, and validation. So let’s implement this step by step.

Step1: Import the ReactiveFormsModule

First we will import the ReactiveFormsModule to the app.module.ts file to create reactive forms.

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

imports: [
    BrowserModule, ReactiveFormsModule
],

Now we will create code for the app.component.ts file. We will also make changes to the app.component.ts file to import the FormGroup, FormBuilder, Validators modules from @angular/forms

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  angularForm: FormGroup;
   constructor(private formbuild: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angularForm= this.formbuild.group({
       empName: ['', Validators.required ]
    });
  }
}

Here we have used FormBuilder and created a constructor and instantiate the form builder to handle the form validation for form input name empName.

Step2: Create Form and Handle Validation

Now inside app.component.html file file, we will create the Form HTML with input and attribute to handle form validation.

<div class="container">
  <h2>Angular Reactive Form Validation</h2>
  <form [formGroup]="angularForm" novalidate>
      <div class="form-group">
        <label class="center-block">Employee Name:
          <input class="form-control" formControlName="empName">
        </label>
      </div>
      <div *ngIf="angularForm.controls['empName'].invalid && (angularForm.controls['empName'].dirty || angularForm.controls['empName'].touched)" class="alert alert-danger">
          <div *ngIf="angularForm.controls['empName'].errors.required">
          Employee name is required.
        </div>
      </div>
	  <div class="form-group">
        <button type="submit"
        [disabled]="angularForm.pristine || angularForm.invalid" class="btn btn-success">
        Save
      </button>
      </div>
</form>
</div>

Save the code and go to the browser and see the form with validation.

You may also like: