2017-04-18 44 views
0

我正在使用formGroup进行表单验证angular2.I正在对电话号码进行验证。我希望验证消息仅在用户离开字段/选项卡时才显示现在,验证工作正常,但验证信息即使在我专注于该领域时也会出现。 例如,如果我尝试更改电话号码并使数字等于10,它会引发错误(尽管我没有标签出来)。我只希望在显示时显示错误。任何想法,我在这里失踪。ANgular2-仅在用户离开字段时显示验证消息

<form [formGroup]="paymentDetailsForm"> 
    <md-input formControlName="officePhone" placeholder="Primary Contact Phone" name="officePhone" [(ngModel)]="paymentform.officePhone" (blur)="registerChaseUser()" (keyup)="numberKeyed($event.target.value)" [restrictKey]="'^[0-9]+$'" noSpace="true" maxlength="14" required></md-input> 
     <span *ngIf="!paymentDetailsForm.controls['officePhone'].valid && (!paymentDetailsForm.controls['officePhone'].pristine || paymentDetailsForm.controls['officePhone'].touched || showPaymentError) && paymentform.officePhone.length == 0" class="validation validation-fix">This field is required.</span> 
     <span *ngIf="(paymentform.officePhone.length < 14) && (paymentform.officePhone.length > 0) && (!paymentDetailsForm.controls['officePhone'].pristine || paymentDetailsForm.controls['officePhone'].touched)" class="validation validation-fix">Please enter a full 10-digit phone number.</span> 
    </form> 
+0

如果您检查感动不应该工作? – LLL

+0

它工作正常,但即使在我尝试更改数字时也会报错。 –

回答

1

尝试使用模糊

<input (blur)="onBlur()" (focus)="onFocus()"> 

,然后激活仅当的onblur被称为消息。

+0

嗨,你应该试试'ngTouch' – Houtan

0

你应该尝试 'ngTouch'

instead of "|| paymentDetailsForm.controls['officePhone'].touched" 
should write "&& paymentDetailsForm.controls['officePhone'].touched" 

例如:

  <form *ngIf="active" id="contactForm" (ngSubmit)="onContactSubmit()" [formGroup]="contactForm"> 
       <div class="row"> 
        <div class="col-sm-6 form-group"> 
         <label for="first-name"> First Name</label> 
         <input class="form-control" type="text" formControlName="firstName"> 
         <p *ngIf="!contactForm.controls.firstName.valid&&contactForm.controls.firstName.touched" class="alert alert-danger"> 
          firstname is required 
         </p> 
        </div> 
        <div class="col-sm-6 form-group"> 
         <label for="last-name"> Last Name</label> 
         <input class="form-control" type="text" formControlName="lastName"> 
         <p *ngIf="!contactForm.controls.lastName.valid&&contactForm.controls.lastName.touched" class="alert alert-danger">lastname is required</p> 
        </div> 
       </div> 
      </form> 
相关问题