1

我正在尝试为 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>
4

0 回答 0