Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular5 Custom Validator for Date Min

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')],
    });
like image 393
Vince Avatar asked Mar 14 '18 17:03

Vince


People also ask

How do you validate a date in reactive form?

Use the DatePipe in the app. component (or the component you want it) to set the current date and format the date values. Set the default date values in the ngOnInit function. Use a form as the parent element of the inputs (not necessary though).

What must be returned from a custom validator function?

The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.


1 Answers

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')]],
like image 121
Vince Avatar answered Sep 20 '22 10:09

Vince