Angular 2,4,5+ Input Mask with Validation

血红的双手。 提交于 2020-01-03 03:22:36

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/48151348/angular-2-4-5-input-mask-with-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!