我在angular2.I中使用formGroup进行表单验证。我正在对电话号码进行验证。我希望仅在用户离开字段/标签时才显示验证消息。现在,验证工作正常,但是即使我专注于该领域,也会出现验证消息。 对于ex.-如果我尝试更改电话号码并使数字等于10,它会抛出错误(虽然我没有标签)。我希望只有当我标签出来时才会显示错误。不知道我在这里缺少什么。
<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 :(得分:1)
尝试使用模糊
<input (blur)="onBlur()" (focus)="onFocus()">
然后仅在调用onblur时激活消息。
答案 1 :(得分: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>