angular4 自定义表单验证Validator

表单的验证条件有时候知足不了需求就能够自定义验证函数

惟一要求返回是ValidatorFnui

export interface ValidatorFn{
 (c:AbstractControl):ValidationErrors | null
}

export declare type ValidationErrors={
 [key:string]:any
}

由上能够发现:this

VilidatorFn的参数是AbstrctControl类型,返回类型是ValidatorErrors类型spa

所以在设计自定义表单验证函数时,必须return一个【参数为AbstrctControl类型,而返回结果是ValidatorErrors类型】的函数设计

 

具体实现:code

如下场景是比较两个密码是否一致component

//Compare.validator.ts

export class CompareValidators{
    static match(targetField:string):ValidatorFn{
       return (self:AbstractControl):{[key:string]:any}=>{    //这里严格按照ValidatorFn的声明来
         let _form=self.parent;
         if(_form){
            let targetControl:AbstractControl=_form.controls[targetField];
            if(targetControl.value && self.value!=targetControl.value){   //若是两个值不一致
                  return {match:''}
            }
         }
      }
   }
}

 

//xx.component.ts

export class xxComponent implements OnInit{ thatForm:FormGroup; ngOnInit(){ this.thatForm=this.formBuilder.group({ password:['',[Validators.required]], confirmPassword:['', [Validators.required,CompareValidators.match('password')]] }) } }
相关文章
相关标签/搜索