Add 10 Digit Mobile / Phone Number Validation in Angular 12

Angular phone number validation tutorial. This quick tutorial will teach you how to validate a mobile number with 10 digit value validation in the Angular application using the validators API’s pattern method.

A form may contain various input types based on the information needed to extract from the user. Throughout this guide, you will create a small form, add a phone/mobile number input in the form using the Reactive forms.

We will create the form using the reactive forms API and explicitly use the Validators class to validate the mobile number. A validator class offers a set of ready-made validators that are useful and works well with form controls.

We will explain bit by bit how to integrate 10 digit phone number validation in the Angular app using reactive forms and regular expression.

How to Implement 10 Digit Mobile / Phone Number Validation in Angular

  • Step 1: Configure Angular CLI
  • Step 2: Install Angular App
  • Step 3: Validate Mobile Number
  • Step 4: Create Form with Validation
  • Step 5: Run Development Server

Configure Angular CLI

Ensure that you have installed the node runtime environment and npm package manager on your development system.

After that, type and execute the given command to install the Angular CLI.

npm install -g @angular/cli

If Angular CLI is already configured, then skip this step.

Install Angular App

Next, you have to install a new angular project, you require to type and execute the following command.

ng new ng-form

After you ran the suggested command, it will generate a skeleton project within the folder ng-demo with a bunch of files.

After you ran the suggested command, it will generate a skeleton project within the folder ng-demo with a bunch of files.

Get into the project folder.

cd ng-form

To validate phone input, we require to create a form with input type text, hence go to app.module.ts file and import the ReactiveFormsModule and FormsModule together from ‘@angular/forms’ pacakge.


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


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

export class AppModule { }

Validate Mobile Number

To create form object and validate with regular expression, make sure to import Validators, FormBuilder and FormGroup APIs. Also, use the getter method to access the form control.

Add, code in app.component.ts file.

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

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

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

export class AppComponent {
  public fg: FormGroup;
  
  constructor(private fb: FormBuilder) {
    this.fg = fb.group({
      phone: ['', [Validators.required, Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")]]
    })
  }
    
  get p(){
    return this.fg.controls;
  }
   
  onFormSubmit(){
    alert(this.fg.value);
  } 
}

Create Form with Validation

Now that we are left with one more thing build a form with the help of formGroup, create a phone form control.

We will show the error message to the user just below the form control name and display the phone number required and ten-digit mobile validation messages.

Ad code in app.component.html file.

<form [formGroup]="fg" (ngSubmit)="onFormSubmit()" novalidate>
  <div class="form-group mb-3">
    <label>Phone/Mobile No.</label>
    <input type="text" formControlName="phone" class="form-control mb-3">

    <div *ngIf="p.phone.touched && p.phone.invalid" class="alert alert-danger">
      <div *ngIf="p.phone.errors?.required">Mobile number is required</div>
      <div *ngIf="p.phone.errors?.pattern">Provide 10 digit phone number</div>
    </div>
  </div>

  <button class="btn btn-primary" type="submit" [disabled]="!fg.valid">Submit</button>
</form>

Run Development Server

We are about to type the given below command on the command prompt, after that hit enter and start the angular development server.

ng serve

Head over to browser, paste the provided url and test the app.

http://localhost:4200

Add 10 Digit Mobile / Phone Number Validation in Angular 12

Summary

A regular expression is a string of characters that identifies search patterns. We used the regex to validate the mobile number in the angular app.

Also, we showed you how to configure and use reactive forms to create the phone number field in angular forms.