Angular自定义验证指令-错误行为不符合预期

时间:2019-04-11 10:06:38

标签: angular angular2-directives

我尝试在Angular 7.0.5中编写一个自定义验证器,但是我无法获取和显示错误。

试图调试代码,并在google和stackoverflow中搜索了答案或提示。

在我使用的模板下面:

<form #formWithDirective="ngForm" name="formWithDirective">
  <input ngModel #desiredWithDirective="ngModel" inFuture="2018-04-27"
    type = "date"
    name = "desiredWithDirective">
  <div *ngIf="desiredWithDirective.errors?.future">
    {{ desiredWithDirective.errors | json }}
  </div>
</form>

指令:

import { Directive, forwardRef, Input } from '@angular/core';
import { Validator, AbstractControl, ValidationErrors, NG_VALIDATORS } from '@angular/forms';
import { MyValidators } from './my-validators';

@Directive({
  selector: '[ngModel][inFuture],[formControl][inFuture],[formControlName][inFuture]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => FutureDirective),
    multi: true
  }]
})
export class FutureDirective implements Validator {
  @Input()
  inFuture: string;

  constructor() { }

  validate(control: AbstractControl): ValidationErrors | null {
    let date: Date;
    if (this.inFuture !== '') {
      date = new Date(this.inFuture);
    }

    return MyValidators.isFuture( date )( control );
  }

  registerOnValidatorChange?(fn: () => void): void;
}

以及inFuture函数的实际实现:

import { ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';

export class MyValidators {
  static readonly isFuture: (condition?: Date) => ValidatorFn
    = (condition?: Date): ValidatorFn => (control: AbstractControl): ValidationErrors | null => {
      if (control.value === null || control.value === '') {
        return null;
      }

      const selectedDate = new Date(control.value);
      const currentDate = (condition == null) ? new Date() : condition;
      const isFuture = selectedDate > currentDate;

      return isFuture
        ? null
        : { 'future': { currentDate, selectedDate } };
    }
}

如果我选择过去的日期,我希望显示一个错误。但是没有显示错误。如果我调试代码并在Chrome控制台中执行MyValidators.isFuture( date )( control );,则会收到以下错误:

Uncaught ReferenceError: MyValidators is not defined
    at eval (eval at push../src/app/my-validators/future.directive.ts.FutureDirective.validate (future.directive.ts:25), <anonymous>:1:1)
    at FutureDirective.push../src/app/my-validators/future.directive.ts.FutureDirective.validate (future.directive.ts:25)
    at forms.js:792
    at forms.js:608
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:608)
    at forms.js:573
    at forms.js:608
    at Array.map (<anonymous>)
    at _executeValidators (forms.js:608)

任何有关如何解决此问题的提示将不胜感激。

1 个答案:

答案 0 :(得分:1)

好吧,我在此stackblitz中没有进行任何更改,它可以正常工作,但在调用该函数时仍会出现相同的控制台错误。由于您没有共享ngModule:您不是只是忘记声明指令了吗?