Angular5 Custom Validator for Date Min

Vince picture Vince · Mar 14, 2018 · Viewed 9.6k times · Source

I'm trying to create a validator for date input.

so I've wrote this piece of code but it's not working as intended!

export class CustomValidators {
  static dateMinimum(date: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (control.value == null) {
        return null;
      }

      const controlDate = moment(control.value, FORMAT_DATE);

      if (!controlDate.isValid()) {
        return null;
      }

      const validationDate = moment(date);

      return controlDate.isAfter(validationDate) ? null : {
        'date-minimum': {
          'date-minimum': validationDate.format(FORMAT_DATE),
          'actual': controlDate.format(FORMAT_DATE)
        }
      };
    };
  }
}

I'm getting this error

ERROR Error: Expected validator to return Promise or Observable.at toObservable (forms.js:749)

I don't really know which thing is not correct... I've found many examples on how to create a custom validators without parameters, but none with parameters...

I need to use the validators like this:

    this.projectForm = this.builder.group({
      date: ['', Validators.required, CustomValidators.dateMinimum('2018-12-12')],
    });

Answer

Vince picture Vince · Mar 14, 2018

everything was working fine....

the problem was in the form creation itself...

date: ['', Validators.required, CustomValidators.dateMinimum('2018-12-12')],

should be

date: ['', [Validators.required, CustomValidators.dateMinimum('2018-12-12')]],