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')]] }) } }
相關文章
相關標籤/搜索