Ramco Ramco

Ramco Ramco

  • 438
  • 3.1k
  • 436.8k

Custom Directive in Angular 17

Jun 27 2024 7:04 AM

Hi

  How to use below code to compare 2 dates using custom directive. Where i should write the below code so it can be used in  any component where Data validation of this type is required.

import {FormGroup, ValidatorFn, Validators} from '@angular/forms';

export function creatDateRangeValidator(): ValidatorFn {
    return (form: FormGroup): ValidationErrors | null => {

        const start:Date = form.get("startAt").value;

        const end:Date = form.get("endAt").value;

        if (start && end) {
            const isRangeValid = (end.getTime() - start.getTime() > 0);

            return isRangeValid ? null : {dateRange:true};
        }

        return null;
    }
}

Thanks


Answers (2)