mirror of
https://dev.azure.com/hugendubel/ISA/_git/ISA-Frontend
synced 2025-12-28 22:42:11 +01:00
31 lines
1.3 KiB
TypeScript
31 lines
1.3 KiB
TypeScript
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
|
|
import { isValid, isBefore, isAfter } from 'date-fns';
|
|
|
|
/**
|
|
* Validator function to check if a date value is within the specified bounds.
|
|
*
|
|
* This validator performs the following checks:
|
|
* - If the control value is empty, the validation passes.
|
|
* - If the date is invalid, a validation error with {invalidDate: true} is returned.
|
|
* - If a minimum date is provided and the control date is before it, a validation error with {minDate: true} is returned.
|
|
* - If a maximum date is provided and the control date is after it, a validation error with {maxDate: true} is returned.
|
|
*
|
|
* @param min - The minimum allowed date (inclusive). Optional.
|
|
* @param max - The maximum allowed date (inclusive). Optional.
|
|
* @returns A ValidatorFn that returns a ValidationErrors object if the date is out of bounds, otherwise null.
|
|
*/
|
|
|
|
// TODO: Utils Auslagern
|
|
export function dateBoundsValidator(min?: Date, max?: Date): ValidatorFn {
|
|
return (control: AbstractControl): ValidationErrors | null => {
|
|
const date: Date | null = control.value ?? null;
|
|
if (!date) return null;
|
|
|
|
if (!isValid(date)) return { invalidDate: true };
|
|
if (min && isBefore(date, min)) return { minDate: true };
|
|
if (max && isAfter(date, max)) return { maxDate: true };
|
|
|
|
return null;
|
|
};
|
|
}
|