关于angular2的异步验证器的实现

在实际开发需求中可能会遇到对表单某一字段通过请求后端接口的方式来实现验证,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 | Observable { // 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


            {{ roleModalList.RoleName | translate }}
            
            
                
                
                    
                        {{ roleModalList.verification_Role_Name | translate }}
                    
                    
                        {{ roleModalList.verification_Role_Name_Repeat | translate }}
                    
                    
                        
                    
                
            

        

你可能感兴趣的:(关于angular2的异步验证器的实现)