Angular 2,4,5+ Input Mask with Validation

2019-06-06 23:10发布

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

1条回答
forever°为你锁心
2楼-- · 2019-06-06 23:34

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>
查看更多
登录 后发表回答