Search code examples
angularangular-forms

How to implement a custom date validation for Out of Stock days


I am trying to implement a custom date validator where I can check if the date entered is not in a list of invalid dates (array of custom dates, ex: ['08/20', '08/24', '08/31']) (Out of Stock) using Angular reactive forms.

My validator looks like this:

export function OutOfStockValidator(invalidDates: any): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (!invalidDates) { return null; }
        let isInvalid = false;
        for (const i in invalidDates) {
            const d = moment(control.value).format('MM' ) + '/' + moment(control.value).format('DD');
            if (d == invalidDates[i]) { isInvalid = true; }
        }

        return isInvalid ? { outOfStock: true } : null;
    };
}

This is how the definition of the control looks like:

this.form = this._formBuilder.group({
    installDate: new FormControl(null, [Validators.required, OutOfStockValidator(this._order.InvalidDates['CARPET_AM'])]),
    ...
});

Here is my template:

<div class="form-group">
    <div class="row">
        <label [for]="installDate" class="col-md-12 col-form-label font-weight-bold">Install Date</label>
        <div class="col-md-12">
            <kendo-datepicker #installDate formControlName="installDate" placeholder="" class="form-control col-md-6" [min]="today">
                <ng-template kendoCalendarMonthCellTemplate let-date>
                    <span [ngClass]="isInvalidDate(date)">{{date.getDate()}}</span>
                </ng-template>
            </kendo-datepicker>
        </div>
    </div>
    <div *ngIf="submitted && f.installDate.outOfStock" class="invalid-feedback d-block">
        <p>Selected date is not available for selection</p>
    </div>
 </div>

The widget works good, but I can not display my custom message: Selected date is not available for selection.

Any idea? Thanks!


Solution

  • The problem is that you are not checking the error properly in the *ngIf.

    This *ngIf="submitted && f.get('installDate').errors?.outOfStock" should have the desired effect.