如何对formGroup Angular 2进行调用方法验证?

时间:2018-06-18 18:43:36

标签: angular

我有表格:

this.changePasswordForm = this.formBuilder.group({
      'passwordNew': ['', ValidationService.passwordValidator], matchingPasswords('passwordNew', 'passwordNewConfirmation')(this)]]
});

我尝试调用的自定义验证函数:

export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
  return (group: FormGroup): {
    [key: string]: any
  } => {
    let password = group.controls[passwordKey];
    let confirmPassword = group.controls[confirmPasswordKey];

    if (password.value !== confirmPassword.value) {
      return {
        mismatchedPasswords: true
      };
    }
  }
}

如何在matchingPasswords内传递当前表单?我尝试使用this

'passwordNewConfirmation')(this)

1 个答案:

答案 0 :(得分:1)

ValidatorFn函数接受当前控件作为参数。您可以使用它来访问表单组。

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

你的功能如下:

export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
  return (control: AbstractControl): {
    [key: string]: any
  } => {
    if(!control.parent){
     return null;
    }
    let group = control.parent;
    let password = group.controls[passwordKey];
    let confirmPassword = group.controls[confirmPasswordKey];

    if (password.value !== confirmPassword.value) {
      return {
        mismatchedPasswords: true
      };
    }
  }
}

注册时,this不需要:

this.changePasswordForm = this.formBuilder.group({
      'passwordNew': ['', [ValidationService.passwordValidator, matchingPasswords('passwordNew', 'passwordNewConfirmation')]]
});