Madasu K
Madasu K

Reputation: 1863

angular input type datetime-local validation

In my angular application for date time selection I am using input type="datetime-local".

 <input id="field_bookingTime" type="datetime-local" class="form-control" name="bookingTime" [(ngModel)]="bookingTime"
   required/>

Now I need to disable the dates that are previous to current date and the dates that are 3 days next to current date. For example for min, I have added validations as shown below. But the validations are not working, still the previous dates are getting enabled in the displayed calendar.

currentDate = new Date();

     <input [min]="currentDate" id="field_bookingTime" type="datetime-local" class="form-control" name="bookingTime" [(ngModel)]="bookingTime"
       required/>

Upvotes: 1

Views: 6109

Answers (3)

abd995
abd995

Reputation: 1839

<input> elements of type datetime-local accepts values for min and max as string in yyyy-MM-ddThh:mm format only. Since new Date() returns a string which is not in the correct format min and max won't work. Just convert the date to the correct format like this.

currentDate = new Date().toISOString().substring(0, 16);

Here we are converting the date to the desired format first by converting it to a simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long and then removing the chars after yyyy-MM-ddThh:mm

Upvotes: 2

Stol
Stol

Reputation: 179

I would recommend writing a custom validator for the form control. Min and max have bad browser support, this goes for datetime-local aswell though.

    function dateValidator(c: FormControl) {
        // Not sure if c will come in as a date or if we have to convert is somehow
        const today = new Date();
        if(c.value > today) {
            return null;
        } else {
            return {dateValidator: {valid: false}};
        }
    }
    ...
    myForm = this.formBuilder.group({
        date: ['', dateValidator]
    })
    ...

Upvotes: 2

Srdjan
Srdjan

Reputation: 582

Try to format your date with dashes:

Example:

pipe = new DatePipe('en-US');

minDate = new Date();
minDateOut = pipe.transform(minDate, 'yyyy-MM-dd');

maxDate = new Date(minDate.getTime() + (1000 * 60 * 60 * 24 * 3));
maxDateOut = pipe.transform(maxDate, 'yyyy-MM-dd');


<input 
    [min]="minDateOut" 
    [max]="maxDateOut" 
    id="field_bookingTime" 
    type="datetime-local" 
    class="form-control" 
    name="bookingTime" 
    [(ngModel)]="bookingTime"
    required/>

Or just use any other date format without spaces...

Upvotes: 0

Related Questions