ng4 自定义表单验证Validator

表单的验证条件有时候满足不了需求就可以自定义验证

要求:返回是ValidatorFn

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


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

具体实现:

export class CompareValidators{
    static match(targetField:string):ValidatorFn{
       return (self:AbstractControl):{[key:string]:any}=>{
         let _form=self.parent;
         if(_form){
            let targetControl:AbstractControl=_form.controls[targetField];
            if(targetControl.value && self.value!=targetControl.value){
                  return {match:''}
            }
         }
      }
   }
}
thatForm:FormGroup;
this.thatForm=this.formBuilder.group({
    password:['',[Validators.required]],
    confirmPassword:['',[Validators.required,CompareValidators.match('password')]]
})

  

猜你喜欢

转载自www.cnblogs.com/artimis/p/9020992.html