Angular 12 Mask Input Control to Enter Specified Format String/Values

Masking on the form controls like input, allows a user to enter predefined patterns. Adding a mask-like Number, Alphanumeric, Date etc prevents misinformation submission informs and also helps users to make data entry more friendly.

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular 12 and Angular 13

We can add validation to show errors after the user enters a wrong value, but this process takes unnecessary time to validate and even network consumption if validation is server-side. Masking helps in validating data in real-time and filling up correct details in specified formats.

In this guide, you will learn how to easily add Pattern making with various examples in the Angular application. W will be using a profound library known as iMask JS in our Angular application. You can easily add some predefined masks on input controls also create custom patterns with ease in few steps.

Let’s get started!

How to Add Pattern Mask on Input Fields in Angular App?

Step 1 – Create Angular App
Step 2 – Install iMask Js & Bootstrap Library Package
Step 3 – Update App Module
Step 4 – Phone, Email, Number, Username, Function, Date, Range Numbers Mask Example
Step 5 – Run Angular App

 

Step 1 – Create Angular App

To enable the ng command in the terminal window, make sure to instal the angular cli tool. If you already have, you can update it as well.

# Install NG CLI
npm install -g @angular/cli

#Update NG CLI
ng update

Afterwards, you can hit the following command to create a new angular project with the name provided:

ng new angular-mask-app

Move inside the application folder

cd angular-mask-app

 

Step 2 – Install iMask Js & Bootstrap Library Package

After creating the Angular app, we will install the Angular adapter plugin for iMask Js. Also install the bootstrap package to quickly style your app.

Execute the following npm command to install the package in our app:

npm install angular-imask bootstrap

To use bootstrap style, open the angular.json file update the "styles" property:

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

Step 3 – Update App Module

Next, update the App Module with IMaskModule to use its directives and functions. Open the app.module.ts file and update as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IMaskModule } from 'angular-imask';

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

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

It will create a simple native Input control, having a number mask on it. The user will not be able to enter anything else Numbers.

Let’s have a look at various types of Mask implementation based on built-in Masks, Pattern Regex based Masks, Functions Masks and String masks as well.

We will also discuss how to use hooks provided by iMask to implement Mask on any existing Input control without any major modifications.

Step 4 – Phone, Email, Number, Username, Function, Date, Range Numbers Mask Example

We have updated the App.js function component to display various types of input controls with various Masks to restrict unintended values in the form controls.

We covered the following in our example implementation:

  • Number Mask
  • Phone Mask using String
  • Number (Range From-To) Mask
  • Date Mask
  • Email Address Mask using Regex
  • Email or Phone Mask using Min Max props
  • Custom(No Space, Only AlphaNumeric) Mask using functions

Update Component Class

Open the app.component.ts file to include the following variables, functions and Masking configuration for the above-mentioned controls.

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

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

  constructor() { }

  // Number Mask
  numberMask = { mask: IMask.MaskedNumber }

  // Phone Number Mask
  phoneMask = { mask: "+{00}(0000)00-0000" };

  // Date Number Mask
  dateMask = { mask: IMask.MaskedDate };
  minDate = new Date();
  maxDate = new Date();

  //Email Mask
  emailMask = {
    mask: /^\S*@?\S*$/
  };

  customMask = {
    mask: this.customMaskFunc
  }

  customMaskFunc(value: string) {
    var pattern = new RegExp(/^[a-z0-9]+$/i);
    console.log(value, pattern.test(value));
    return pattern.test(value);
  };

  onAccept() {
    console.log('on accept')
  }
  onComplete() {
    console.log('on complete');
  }
}

Update HTML Template

Now, head towards the HTML template to add the various form controls with respective Masking implemented. Update the app.component.html file:

<div class="container">

  <div class="form-group">
    <label>Number Mask</label>
    <input [imask]="numberMask" class="form-control" [unmask]="true" (accept)="onAccept()" (complete)="onComplete()" />
  </div>

  <div class="form-group">
    <label>Phone Mask</label>
    <input [imask]="phoneMask" class="form-control" [unmask]="true" (accept)="onAccept()" (complete)="onComplete()" />
  </div>

  <div class="form-group">
    <label>Number (Range From-To) Mask</label>
    <input [imask]="numberMask" [min]="'100'" [max]="'2000'" class="form-control" [unmask]="true" (accept)="onAccept()"
      (complete)="onComplete()" />
  </div>

  <div class="form-group">
    <label>Date Mask</label>
    <input [imask]="dateMask" [min]="minDate" [max]="maxDate" class="form-control" [unmask]="true" (accept)="onAccept()"
      (complete)="onComplete()" />
  </div>

  <div class="form-group">
    <label>Email Address Mask</label>
    <input [imask]="emailMask" class="form-control" [unmask]="true" (accept)="onAccept()" (complete)="onComplete()" />
  </div>

  <div class="form-group">
    <label>Custom(No Space, Only AlphaNumeric) Mask</label>
    <input [imask]="customMask" class="form-control" [unmask]="true" (accept)="onAccept()" (complete)="onComplete()" />
  </div>

</div>

You can see the working demo on StackBlitz on the tutorial’s end.

Step 6 – See in Action

Finally, you can run the application by hitting ng serve --open to start the application at the following URL:

http://localhost:4200

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments