Mobile Number Validation Using Angular and Bootstrap

Introduction

In this article, we learn steps to implement 10-digit mobile number validation in the angular app using the angular phone number validation pattern. Here we validate mobile numbers in Angular with reactive forms. Reactive forms offer a model-driven path for managing form inputs whose values change over time. It explains the steps to create and update an essential form control for 10-digit mobile number validation in Angular. Here, we create a simple dynamic form where you can use a mobile number validation pattern under the angular application’s component.

Note. Before going through this session, please visit my previous article related to Angular applications as mentioned below.

Angular articles

Step 1. Import Reactive Forms Module

Here we import the reactive forms module, open src/app/app.module.ts, and update the code in the file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

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

Step 2. Update TypeScript Template

Here, we import FormBuilder, FormGroup, and Validators from ‘@angular/forms’, then define the form using FormGroup use the mobile number pattern using the regex, and bind it to the submit method. Add code in src/app/app.component.ts file.

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

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

  constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      mob: ['', [Validators.required, Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")]]
    });
  }

  get m() {
    return this.myForm.controls;
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}

The mobile number validation logic is configured here.

this.myForm = this.formBuilder.group({
  mob: ['', [Validators.required, Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")]]
});

Step 3. Update HTML File

Here, we create a form using form Group and ngSubmit directives and define the phone number input field using the form control name directive. Also, define the inline phone number validation with the required 10-digit mobile number validation message. Add code in the src/app/app.component.html file.

<div class="card bg-danger text-white">
  <div class="card-body text-center">
    Mobile Number Validation Using Angular
  </div>
  </div>
  <div class="container mt-5">
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
      <div class="form-group">
        <label>Enter Mobile number: </label>
        <input type="text" formControlName="mob" class="form-control mb-2">
        <div *ngIf="m.mob.touched && m.mob.invalid" class="alert alert-danger">
          <div *ngIf="m.mob.errors?.required">Please enter mobile number</div>
          <div *ngIf="m.mob.errors?.pattern">Entered Mobile number is not 10 digit</div>
        </div>
        <div class="toast show" 
        style="position:fixed;
               top: 70%;
               left: 50%;
               width:30em;
               height:10em;
               margin-top: -9em; /*set to a negative number 1/2 of your height*/
               margin-left: -15em; /*set to a negative number 1/2 of your width*/
               border: 1px solid #ccc;
               background-color: #f3f3f3;
               color: red;
               font-weight:900;
               font-size:larger;" 
               *ngIf="m.mob.touched && m.mob.invalid">
               <div class="toast-header">
                Mobile Number Validation Using Angular
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
              </div>
          <div class="toast-body" *ngIf="m.mob.errors?.required">Please enter mobile number</div>
          <div class="toast-body" *ngIf="m.mob.errors?.pattern">Entered Mobile number is not 10 digit</div>
        </div>
      </div>
      <div class="d-grid mt-3">
        <button class="btn btn-primary" [disabled]="!myForm.valid" type="submit">Send Message</button>
      </div>
    </form>
  </div>

Here the validations are 2 types. One is if the mobile number is empty and the other is if the entered mobile number is not 10 digit mobile number.

<div *ngIf="m.mob.touched && m.mob.invalid" class="alert alert-danger">
          <div *ngIf="m.mob.errors?.required">Please enter mobile number</div>
          <div *ngIf="m.mob.errors?.pattern">Entered Mobile number is not 10 digit</div>
</div>


-----------------------

<div class="toast show" 
        style="position:fixed;
               top: 70%;
               left: 50%;
               width:30em;
               height:10em;
               margin-top: -9em; /*set to a negative number 1/2 of your height*/
               margin-left: -15em; /*set to a negative number 1/2 of your width*/
               border: 1px solid #ccc;
               background-color: #f3f3f3;
               color: red;
               font-weight:900;
               font-size:larger;" 
               *ngIf="m.mob.touched && m.mob.invalid">
               <div class="toast-header">
                Mobile Number Validation Using Angular
                <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
              </div>
<div class="toast-body" *ngIf="m.mob.errors?.required">Please enter mobile number</div>
<div class="toast-body" *ngIf="m.mob.errors?.pattern">Entered Mobile number is not 10 digit</div>
</div>

Here, we call the onSubmit() method using formGroup and ngSubmit directives.

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
----
----
</form>

Step 4. Add Bootstrap to make the page responsive

Add code in the index.html file,

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title Service Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 5. Update tsconfig.json file

Set the noPropertyAccessFromIndexSignature property to false under compiler options in the tsconfig.json file.

{
  "compileOnSave": false,
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": false
  }
}

Note. By default, the property is set to true. If the above property is not set to false, then we get an error while running the Angular application.

The error details: No Property Access From Index Signature.

Property 'mob' comes from an index signature, so it must be accessed with ['mob'].

Property 'pattern' comes from an index signature, so it must be accessed with ['pattern'].

-----------------

Property '****Name' comes from an index signature, so it must be accessed with ['****Name']

Output

Here, we run the command (ng serve) to start the angular app server.

The result is shown the first time the page loads.

Angular app server

Check the mobile number validation.

 Number validation

How it performs is shown below.

Performs

Summary

In this write-up, we have learned the details below.

  • Steps to add phone number validation with 10-digit mobile number validation using Angular.
  • Know about dynamic reactive form in Angular.

Thank You & Stay Tuned For More