I am dealing with two dates, namely an arrival date and an exit date. I am attempting to implement custom validation where the exit date cannot be earlier than the arrival date. If it is earlier, then display an error message. Please refer to the code snippet below.
component.ts file:
arrivalDate: ['', [Validators.required, this.validateArrivalDate()]],
exitDate: ['', [Validators.required, this.validateExitDate()]],
validateExitDate(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (this.currentTravelFormGroup !== undefined) {
const exitDate = this.currentTravelFormGroup.controls['exitDate'].value;
const arrivalDate = this.currentTravelFormGroup.controls['arrivalDate'].value
if (exitDate <= arrivalDate) return { requiredToDate: true };
}
};
}
validateArrivalDate(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (this.currentTravelFormGroup !== undefined) {
const exitDate = this.currentTravelFormGroup.controls['exitDate'].value;
const fexitDate = new Date(exitDate);
const arrivalDate = this.currentTravelFormGroup.controls['arrivalDate'].value;
if (fexitDate <= arrivalDate) return { requiredFromDate: true };
}
};
}
I have set up error messages in HTML as follows:
<mat-error *ngIf="currentTravelFormGroup.get('arrivalDate').hasError('requiredFromDate')">Please provide a valid arrival date</mat-error>
<input class="form-control bgColor" [matDatepicker]="pickerExitDateFromGermany" placeholder="MM/DD/YYYY" [min]="minStartDateFutureTravel" [max]="maxStartDateFutureTravel" formControlName="exitDate" id="exitDate" readonly (click)="pickerExitDateFromGermany.open()"
[ngClass]="{ 'is-invalid': submitted && travelDet.exitDate.errors }">
<mat-datepicker #pickerExitDateFromGermany></mat-datepicker>
<mat-error *ngIf="currentTravelFormGroup.get('exitDate').hasError('requiredToDate')">Please provide a valid exitdate</mat-error>
The current functionality correctly displays error messages for the exit and arrival dates. However, when the arrival date is set to 11/11/2019 and the exit date is set to 10/11/2019 (an error message is displayed below the exit input field). If I change the arrival date to 08/11/2019...
If you spot any issues or have suggestions on how to solve them, please feel free to share your insights. Thank you!