Implement Text Mask In Angular

Introduction:

The Angular Input Mask, often known as a masked textbox, is a component that offers a simple and dependable way to gather user input based on a common mask. You may enter credit card numbers, phone numbers, dates, and other variables in the standard format.

Prerequisites:

Before starting this instruction, ensure that you have npm installed on your computer. We will use npm to find and install the required dependencies for our application. Also required are code editors. The entire course makes use of Visual Studio Code.

Get Started:

Step 1: Set up your project.

In a terminal or command window, enter the following command after choosing the folder where you want to start an Angular project.

ng new text-mask

Step 2: Add bootstrap for styling.

npm install --save bootstrap

Then import bootstrap CSS in your styles.css file.

Step 3: Install ngx-mask in your project.

npm install --save ngx-mask@12

Import NgxMaskModule in the app.module.ts file.

import { NgxMaskModule } from 'ngx-mask';
.
.
.
imports: [
   .
   .
   NgxMaskModule.forRoot()
]

Step 4: Add some text boxes with mask attributes.

<div class="container-block">
  <div class="mb-3">
    <label for="creditCard" class="form-label">Card Number</label>
    <input type="text" class="form-control" id="creditCard" mask="0000 0000 0000 0000">
  </div>
  <div class="mb-3">
    <label for="date" class="form-label">Date</label>
    <input type="text" class="form-control" id="date" mask="00/00/0000">
  </div>
  <div class="mb-3">
    <label for="pan" class="form-label">PAN Card</label>
    <input type="text" class="form-control" id="pan" mask="SSSSS0000S">
  </div>
</div>

In the mask attribute, ‘0’ (zero) is used for numbers and ‘S’ is used for alphabets.

Default patterns:

Code Meaning
0 digits (like 0 to 9 numbers)
9 digits (like 0 to 9 numbers), but optional
A letters (uppercase or lowercase) and digits
S only letters (uppercase or lowercase)
U only letters uppercase
L only letters lowercase

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories