验证新密码不起作用

时间:2018-06-25 14:50:41

标签: angular validation

我有一个用于更改密码的表格:

    <div class="form-group">
        <label for="newPassword">New Password</label>
        <input class="form-control" type="password" formControlName="newPassword">
        <div class="alert alert-danger" *ngIf="newPassword.touched && newPassword.invalid">
           <div *ngIf="newPassword.errors.required">  New password is required </div>
        </div>
    </div>


    <div class="from-group">
        <label for="confirmPassword">Confirm New Password</label>
        <input class="form-control" type="password" formControlName="confirmPassword">
        <div class="alert alert-danger" *ngIf="confirmPassword.touched && confirmPassword.invalid">
            <div *ngIf="confirmPassword.errors.required">  New password is required </div>           
         </div>
        <div class="alert alert-danger" *ngIf="form.invalid &&  form.errors.PasswordsNotMatch">Passwords do not mach</div>
    </div>  

    <button class="btn btn-primary">Change Password</button>

TS文件:

form = new FormGroup({
    oldPassword : new FormControl('', [Validators.required], PasswordValidators.validOldPassword),
    newPassword : new FormControl('', Validators.required),
    confirmPassword : new FormControl('', Validators.required),
  }, PasswordValidators.PasswordsNotMatch);

  get oldPassword () {
    return this.form.get ('oldPassword');
  }

  get newPassword () {
    return this.form.get ('newPassword');
  }

  get confirmPassword () {
    return this.form.get ('confirmPassword');
  }

用于验证新密码的代码在单独的文件中实现:

export class PasswordValidators {

    static PasswordsNotMatch (control: AbstractControl) {
        let newPassword = control.get('newPassword');
        let confirmPassword = control.get ('confirmPassword');

        if (newPassword.value != confirmPassword.value)
            return { PasswordsNotMatch : true };
        return null;
    }
}

这是我在控制台上看到的错误:Cannot read property 'PasswordsNotMatch' of null

您能帮我找出代码中的错误吗?

1 个答案:

答案 0 :(得分:1)

根据提供的代码:

<div class="alert alert-danger" *ngIf="form.invalid &&  form.errors.PasswordsNotMatch">Passwords do not mach</div>

您正在尝试访问FormGroup的errors属性。如果您没有任何错误(https://angular.io/api/forms/AbstractControl#errors),则此属性为null

您应该添加条件以测试您的表单是否具有非null错误属性

*ngIf="form.invalid && form.errors && form.errors.PasswordsNotMatch"