在实际开发需求中可能会遇到对表单某一字段通过请求后端接口的方式来实现验证,angular异步表单验证如下
下面代码以对表单roleName字段进行是否重复校验为例,当用户输入roleName且roleName input框失去焦点后想后端发起请求进行校验操作
component.ts
// 表单控件,updateOn: 'blur'控制失去焦点时才发送请求,减少发送请求数量(updateOn属性有三种情况,详情参见官网)
this.fm = this.fb.group({
roleName: [null, { validators: Validators.required, asyncValidators: this.roleNameValidator.bind(this), updateOn: 'blur' }] // 对于异步请求函数roleNameValidator没有使用箭头函数就会在成丢失this从而报undefined错误,可以在这儿绑定this
});
roleNameValidator(control: FormControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> { // roleNmae repeat 异步校验
// 异步表单验证,验证name是否重复
const pagepram = {
page: 0,
size: this.xTotalCount ? this.xTotalCount : 999
};
const searchData = {
id: null,
name: control.value,
refId: null,
description: null,
obsolete: 0,
createdDateFrom: '',
createdDateTo: '',
generalSearch: null
};
return this.userMgtService.getRoleByQuery(searchData, pagepram).pipe( // 发送请求操作
map(res => {
console.log(res);
const r: any = this.detailModalAction === 'update' && this.updateRoleNameVlue === control.value ? [] : res.body;
const isNameRepeat = r.some(item => item.roleName === control.value);
if (isNameRepeat) {
return { isUsed: true };
} else {
return null;
}
}),
catchError(() => of(null))
);
}
component.html
<nz-form-item nzFlex>
<nz-form-label nzRequired>{{ roleModalList.RoleName | translate }}</nz-form-label>
<!--<span class="colonStyle">:</span>-->
<nz-form-control nzHasFeedback>
<input required class="invalid" [disabled]="isDisabled" autocomplete="off" maxlength="50" formControlName="roleName" nz-input nzSize="default" [(ngModel)]="roleName" name="roleName">
<nz-form-explain *ngIf="fm.get('roleName')?.dirty && fm.get('roleName')?.errors">
<ng-container *ngIf="fm.get('roleName').hasError('required')">
{{ roleModalList.verification_Role_Name | translate }}
</ng-container>
<ng-container *ngIf="fm.get('roleName').hasError('isUsed')">
{{ roleModalList.verification_Role_Name_Repeat | translate }}
</ng-container>
<!--<ng-container *ngIf="fm.get('roleName').hasError('isUsed')">-->
<!--{{ item.verification_User_Names | translate }}-->
<!--</ng-container>-->
</nz-form-explain>
</nz-form-control>
</nz-form-item>