Angular 2验证器未按预期工作

时间:2017-04-25 18:07:16

标签: angular typescript angular2-formbuilder angular-validation

我有这个验证器:

export const PasswordsEqualValidator = (): ValidatorFn => {

  return (group: FormGroup): Observable<{[key: string]: boolean}> => {

    const passwordCtrl: FormControl = <FormControl>group.controls.password;
    const passwordAgainCtrl: FormControl = <FormControl>group.controls.passwordAgain;

    const valid = passwordCtrl.value.password === passwordAgainCtrl.value.passwordAgain;

    return Observable.of(valid ? null : {
      passwordsEqual: true
    });
  };
};

以下表格中使用:

  public signupForm: FormGroup = this.fb.group({
    email: ['', Validators.required],
    passwords: this.fb.group({
      password: ['', Validators.required],
      passwordAgain: ['', Validators.required]
    }, {validator: CustomValidators.passwordsEqual()})
  });

使用它的模板的一部分:

<div formGroupName="passwords">
  <div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
    <label class="label" for="password">Password</label>
    <input class="input" id="password" formControlName="password" type="password">
  </div>
  <div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
    <label class="label" for="password-again">Password again</label>
    <input class="input" id="password-again" formControlName="passwordAgain" type="password">
  </div>
</div>

问题是即使密码匹配,它仍会显示错误。我看了很多不同的类似问题,但大多数人都有点杂乱和过时,所以我想写一个更清洁的解决方案。

我猜测只需要进行一些小调整,但我似乎无法弄明白。

1 个答案:

答案 0 :(得分:4)

试试这个,因为你需要比较2值并且验证器不是异步验证器,你只能返回boolean而不是Observable

export const PasswordsEqualValidator = (): ValidatorFn => {

  return (group: FormGroup): boolean => {

    const passwordCtrl: FormControl = <FormControl>group.controls.password;
    const passwordAgainCtrl: FormControl = <FormControl>group.controls.passwordAgain;

    const valid = passwordCtrl.value === passwordAgainCtrl.value;

    return valid ? null : {
      passwordsEqual: true
    };
  };
};

btw,使用此方法进行最佳实践:

export const PasswordsEqualValidator = (): ValidatorFn => {

  return (group: FormGroup): boolean => {

    const passwordCtrl: FormControl = group.get('password');
    const passwordAgainCtrl: FormControl = group.get('passwordAgain');

    const valid = passwordCtrl.value === passwordAgainCtrl.value;

    return valid ? null : {
      passwordsEqual: true
    };
  };
};

演示:http://plnkr.co/edit/9PzGSIuBhvNz0fpJxTlS?p=preview