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')],
});
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).
The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.
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')]],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With