0

Can I validate phone number's pattern using *ngIf on pattern?

 <div class="input-container">
     <label for="Representative1">* Contact Number</label>
     <input name="r1contact" #r1contact="ngModel" id="Representative1Contact" placeholder="09*********" pattern="^\d{4}-\d{4}-\d{3}$" type="tel" [(ngModel)]="SignUp.AuthorizedRep1Contact" pInputText required/>
     <label *ngIf="!(r1contact.pristine || r1contact.valid)" style="color: red; font-size: 12px; margin-top: 0%"> *Contact Number Required!</label>
     <label *ngIf="!pattern" style="color: red; font-size: 12px; margin-top: 0%">Invalid Format</label>
 </div>
John Roy
  • 67
  • 8

2 Answers2

2

Here is an example for you.

<div class="form-group">
   <label for="name">Mobile Number</label>
   <input type="text" class="form-control" id="mobilenumber"
   required
   [(ngModel)]="model.mobile" name="mobilenumber"
   pattern="[0-9]*"
   minlength="10"
   maxlength="10" 
   #mobile="ngModel">
   <div [hidden]="mobile.valid || mobile.pristine"
      class="alert alert-danger">
      <div [hidden]="!mobile.hasError('minlength')">Mobile should be 10digit</div>
      <div [hidden]="!mobile.hasError('required')">Mobile is required</div>
      <div [hidden]="!mobile.hasError('pattern')">Mobile numberr should be only numbers</div>
   </div>
</div>  

Reference:-

https://cuppalabs.github.io/tutorials/how-to-implement-angular2-form-validations/

Karnan Muthukumar
  • 1,843
  • 1
  • 8
  • 15
1

When you add pattern, it will automatically add as a part of error objects. So just check

 <label *ngIf="!r1contact.error.pattern" style="color: red; font-size: 12px; margin-top: 0%">Invalid Format</label>
Ankur Jain
  • 221
  • 1
  • 6