使用* ngIf验证电话号码格式

时间:2019-02-07 09:10:49

标签: html angular

我可以使用* ngIf on模式来验证电话号码的模式吗?

 <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>

2 个答案:

答案 0 :(得分:1)

这是给你的例子。

<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>  

参考:-

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

答案 1 :(得分:0)

添加模式时,它将自动添加为错误对象的一部分。所以只需检查

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