【问题标题】:Angular custom validation directive - errors does not behave as expectedAngular 自定义验证指令 - 错误的行为不符合预期
【发布时间】:2019-04-11 10:06:38
【问题描述】:

我尝试在 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)

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

【问题讨论】:

  • 你在 app.module.ts 中添加了MyValidators 吗?
  • 它有自己的模块:MyValidatorsModule 女巫声明并导出指令。由于调试器能够在验证器函数内部中断,我假设该部分工作正常。

标签: angular angular2-directives


【解决方案1】:

好吧,我没有更改此 stackblitz 中的任何内容,它工作正常,但在您调用该函数时仍会出现相同的控制台错误。因为你没有分享你的 ngModule:你是不是忘了声明你的指令?

【讨论】:

  • 感谢您的留言。我已经声明并导出了该指令。它有自己的模块 (MyValidatorsModule) - @NgModule({ declarations: [FutureDirective], imports: [ CommonModule ], exports: [FutureDirective] }) export class MyValidatorsModule { }
  • 对不起 - 愚蠢的我;我们有 2019 年……我尝试过错误的日期……非常尴尬。非常感谢您花时间和精力帮助我!
猜你喜欢
  • 2019-03-15
  • 1970-01-01
  • 2011-08-16
  • 2016-08-16
  • 1970-01-01
  • 2013-08-23
  • 2016-03-17
  • 2017-05-26
  • 2014-03-07
相关资源
最近更新 更多