Angular 2 个验证器未按预期工作

Angular 2 validator not working as expected

我得到了这个验证器:

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>

问题是即使密码匹配,它仍然显示错误。我看过许多不同的类似问题,但大多数问题都有些混乱和过时,所以我想编写一个更简洁的解决方案。

我猜只需要做一个小的调整,但我似乎想不出来。

试试这个,因为你需要比较 2 个值并且验证器不是异步验证器,你可以 return 只用 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
    };
  };
};

顺便说一句,将此方法用于最佳实践:

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