6

我得到了这个验证器:

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>

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

我猜只需要进行一些小的调整,但我似乎无法弄清楚。

4

1 回答 1

4

试试这个,因为你需要比较 2 值并且验证器不是异步验证器,你可以只返回布尔值而不是 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

于 2017-04-25T18:21:05.723 回答