简体   繁体   English

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

[英]Angular custom validation directive - errors does not behave as expected

I try to write a custom validator in Angular 7.0.5, but I'm unable to get and display errors.我尝试在 Angular 7.0.5 中编写自定义验证器,但无法获取和显示错误。

Tried to debug the code and searched both google and stackoverflow for answers or hints.尝试调试代码并在 google 和 stackoverflow 上搜索答案或提示。

Below the template I use:在我使用的模板下方:

<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>

The directive:该指令:

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;
}

And the actual implementation of the inFuture function:以及 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 } };
    }
}

I expect that an error is displayed if I select a date in the past.我希望如果我选择过去的日期会显示错误。 But no error is shown.但没有显示错误。 If I debug the code and execute MyValidators.isFuture( date )( control );如果我调试代码并执行MyValidators.isFuture( date )( control ); in chrome console I get the following error:在 chrome 控制台中,我收到以下错误:

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)

Any hint on how to tackle this problem would be much appreciated.任何有关如何解决此问题的提示将不胜感激。

Well I didn't change anything in this stackblitz and it works fine but still gives the same console error when you call the function.好吧,我没有在此stackblitz 中更改任何内容,它运行良好,但在调用该函数时仍会出现相同的控制台错误。 As you didn't share your ngModule: didn't you just forget to declare your directive?由于您没有分享您的 ngModule:您是不是忘记声明您的指令?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM