Angular 2表单验证错误

时间:2017-07-15 06:40:05

标签: angular angular2-forms

在角度2中,我想在用户离开现场区域后才进行客户端验证。这是因为当用户输入电子邮件或电话等字段时,他们总是会在完成输入完整的电子邮件之前收到错误,这不是最佳的用户体验。

目前我使用过

address1: ['', Validators.compose([Validators.required, 
              Validators.maxLength(128), Validators.minLength(5)])],

模板:

<div class="addres">
    <label class="form_label asterisk">Address Line 1</label>
    <textarea class="form_input " formControlName="address1"></textarea>
    <div class="error" *ngIf="addDealerForm.controls['address1'].errors && (addDealerForm.controls['address1'].touched)">
        <div *ngIf="addDealerForm.controls['address1'].hasError('required')">
            Address1 is required.
        </div>
        <div *ngIf="addDealerForm.controls['address1'].hasError('maxlength')">
            Exceeded maximum character length.
        </div>
        <div *ngIf="addDealerForm.controls['address1'].hasError('minlength')">
            Enter minimum character length.
        </div>
    </div>
</div>

帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

我认为你需要在(blur)方法上设置验证。对于前

//组件

 onBlur() {
        this.formControl.get(name).setValidators('', [Validators.minLength(3));
    }

//表格

<textarea class="form_input " formControlName="address1" (blur)="onBlur()"></textarea>

帮助

另见discussion可能有帮助