Angular 9 ngx-input-mask Directive Example to Take Form Fields Mask Input For Validating Phone Numbers,Credit Cards & Dates in Browser Full Project For Beginners

 

 

Simple usage

 

 

Just import in AppModule:

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { InputMaskModule } from "ngx-input-mask";

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

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

 

 

In HTML:

<input
  type="text"
  inputMask="+7 (000) 000-00-00"
  [(ngModel)]="phone"
  name="phone"
/>

 

 

Advanced options

 

 

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import {
  InputMaskModule,
  MaskTemplates,
  MASK_TEMPLATES,
  DEFAULT_MASK_TEMPLATES,
} from "ngx-input-mask";

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

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule, InputMaskModule],
  declarations: [AppComponent],
  providers: [
    {
      provide: MASK_TEMPLATES,
      useValue: {
        ...DEFAULT_MASK_TEMPLATES,
        H: /[ABCEHKMOPTXY]/, // Russian car license plate
        // Put your templates here (NOTICE: There allows keys 1 letter only!)
      } as MaskTemplates,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}
Then you can use it:

<input
  type="text"
  inputMask="H 000 HH 000"
  [(ngModel)]="licensePlate"
  name="licensePlate"
/>

Leave a Reply