Angular 2,4,5+ Input Mask with Validation

Rinold picture Rinold · Jan 8, 2018 · Viewed 11.8k times · Source

How to Validate and show validation message in Angular Template driven aproach?

Answer

Rinold picture Rinold · Jan 8, 2018

step1: Download TextMask directive from npm by command npm i angular2-text-mask --save.

step2: Import and declare the downloaded directive to your component file or in a common module where this directive can be shared with all the project components.

step3: In the component.ts file write the mask pattern as an array. For example:

public mobileNumberMask = ['(', /[0-9]/, /\d/, /\d/, ')', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];

example: masked value (123)456-7890.

Step 4: In the element add the directive attribute such as like, example:

<div class="col-sm-8">
 <input type="text" id="mobileNumber" 
    class="form-control" name="mobileNumber"
    [ngClass]="{'errorMsg': ((mobileNumber.dirty || this.formOnSubmit) && 
    mobileNumber.invalid)}"
    [textMask]="{mask: mobileNumberMask, guide: true}"
    pattern="\(\d{3}\)\d{3}\-\d{4}"                                                
    [(ngModel)]="person.mobileNumber" placeholder="Enter mobile no"
    #mobileNumber="ngModel"
    required  >

 <div [ngClass]="{'errorMessage':!((mobileNumber.dirty || formOnSubmit) && 
   mobileNumber.invalid)}" >
       <span class="customMsg">{{'mobile number is required'}}</span>
 </div>
</div>