Angular Form Validation Example: The Complete Guide

In Angular, we have two kinds of forms, and those are Template Driven Form and Reactive Form. First, we will walk through the best practices to create user-friendly forms and validations using Angular. After that, we will go through each Angular form like template-driven forms and reactive forms validations with the examples. Finally, we will see the fundamental concepts of Angular FormControl, FormGroup, FormBuilder, and different types of built-in validators.

Angular Form Validation

Before we start Angular Forms Validation Example, if you are new to Angular Forms, then check out this Angular Forms Tutorial Example. Forms are almost always present in any website or web application, or mobile app. Forms can perform countless actions like data-entry tasks such as authentication, order submission, or profile creation. However, let’s keep in mind that the real objective of forms in web or mobile applications is to get the data from the user. As it always happens in software development, there are many different ways of sending and handling data on your server.

Template-driven Angular Form Validation

We can add the validation to the template-driven form; you add the same validation attributes with native HTML form validation. Angular uses the directives to match these attributes with the validator functions in the system. Every time the value of the form control changes, Angular runs the validation and generates either the list of validation errors, which results in an INVALID status or null, which leads to the VALID status. Let us take an example, but first, Install Angular.

#1: Install Angular

Type the following command to generate the new Angular project.

ng new ng7validation

 

Angular 7 Form Validation Example Tutorial

Now, go inside the ng7validation folder and create open the folder inside VSCode.

cd ng7validation
code .

Now, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, include the bootstrap 4 inside the angular.json file inside the styles array.

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

#2: Template Driven Angular Form Validation.

Inside the app.module.ts file, we need to add the FormsModule.

// app.module.ts

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 { }

Now, add the following code inside the app.component.ts file.

// app.component.ts

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

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

  onSubmit() {
    alert(JSON.stringify(this.data));
  }
}

When the user submits the form, we will get it here, and from here, we can send the data to the server.

Now, add the validation inside the template, which is the app.component.ts file.

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

Angular Template Driven Form Validation

If the validation errors are there, then the submit button is disabled; if the form status is valid, you can send the form with the values.

#3: Angular Reactive Form Validation

We have seen the Angular Template-driven form validation; now, we will see the Angular Reactive Form Validation.

Reactive Forms

Reactive forms are an Angular technique for creating forms in the reactive style. Angular reactive forms facilitate the reactive style of programming that favors explicit management of the data flowing between a non-UI data model (typically retrieved from a server) and a UI-oriented form model that retains the states of the HTML form controls on the screen. In addition, reactive Forms offer us the ease of using reactive programming patterns, testing, and validation. Let us take an example.

Now, import the ReactiveFormsModule inside the app.module.ts file.

// app.module.ts

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

imports: [
    BrowserModule, ReactiveFormsModule
],

Now, we need to write the code for the app.component.ts file. Remember, this is not a template-driven form. So we will change the code inside the app.component.ts file.

First, we import the FormGroup, FormBuilder, Validators modules from @angular/forms.

Also, create a constructor and instantiate the FormBuilder.

// app.component.ts

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 {
  angForm: FormGroup;
   constructor(private fb: FormBuilder) {
    this.createForm();
  }
   createForm() {
    this.angForm = this.fb.group({
       name: ['', Validators.required ]
    });
  }
}

We have used form builder to handle all the validation. So in that constructor, we are creating a form with the validation rules.

Now, write the following code inside an app.component.html file.

<div class="container">
  <h2>Angular Reactive Form Validation</h2>
  <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="center-block">Name:
          <input class="form-control" formControlName="name">
        </label>
      </div>
      <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
          <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
      </div>
</form>
<p>Form value: {{ angForm.value | json }}</p>
<p>Form status: {{ angForm.status | json }}</p>
</div>

Save the file and go to the browser and see the validation result with the values.

 

Angular Reactive Form Validation

Now, our complete form looks like the below code with the submit button.

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

That’s it for Angular form validation. Thanks for taking it.

Leave a Comment

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