Angular(4):密码匹配验证器无法正常工作

时间:2017-09-03 09:44:22

标签: angular angular-validation

我正在尝试为Angular(4)编写我的第一个自定义验证器。我想我已经正确设置了一切,但缺少了一些东西。验证器根本不起作用。它没有显示任何错误或任何错误。

这是验证器:

export class PasswordValidator {
  static matchPassword(control: AbstractControl): ValidationErrors | null {
    const password = control.get('password').value;
    const passwordConfirmation = control.get('passwordConfirmation').value;
    if (password != passwordConfirmation) {
      console.log('passwords did not match');
      control.get('confirmPassword').setErrors({matchPassword: true})
    } else {
      console.log('successfully matched');
      return null
    }
  }
}

这是验证指令:

@Directive({
  selector: '[passwordDomain][ngModel]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useValue: PasswordValidator,
      multi: true
    }
  ]
})
export class PasswordValidationDirective {

  constructor() {
  }

}

这是使用此验证器的html代码:

<input mdInput
       type="password"
       required
       ngModel name="passwordConfirmation"
       #passwordConfirmation="ngModel"
       passwordDomain
       placeholder="{{'PASSWORD_RECOVERY.PASSWORD_CONFIRMATION' | translate}}">
       <md-error *ngIf="passwordConfirmation.touched && passwordConfirmation.invalid">
                <span *ngIf="passwordConfirmation.errors?.matchPassword">
                      {{'PASSWORD_RECOVERY.MATCH' | translate}}
                </span>
       </md-error>
</md-input-container>

0 个答案:

没有答案