Я пытаюсь написать собственный валидатор в 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 } };
}
}
Я ожидаю, что появится ошибка, если я выберу дату в прошлом. Но ошибка не отображается. Если я отлаживаю код и выполняю MyValidators.isFuture( date )( control );
в консоли 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)
Любая подсказка о том, как решить эту проблему, будет очень признательна.