Home > Enterprise >  Set a minimum date for date field using Javascript
Set a minimum date for date field using Javascript

Time:09-28

My model looks like this

    [Display(Name = "Start Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
    public DateTime BookingStartDate { get; set; }

This is from the View (Create)

<input asp-for="BookingStartDate" min="@DateTime.Now.ToString("dd/MM/yyyy HH:mm")" asp-format="{0:dd/MM/yyyy HH:mm}"  />

When I enter the date '29/09/2022, the warning still say:

Please enter a value greater than or equal to 27/09/2022 20:31.

enter image description here

Whats wrong here. Can you point a way to do this using Javascript?

CodePudding user response:

The answer can be found here:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

Let me quote:

min The earliest date and time to accept; timestamps earlier than this will cause the element to fail constraint validation. If the value of the min attribute isn't a valid string which follows the format YYYY-MM-DDThh:mm, then the element has no minimum value.

This value must specify a date string earlier than or equal to the one specified by the max attribute.

Note the format: YYYY-MM-DDThh:mm

CodePudding user response:

I solve it by adding the type="datetime-local", min, and max value.

<input required type="datetime-local" asp-for="BookingStartDate" 
  min="@DateTime.Now.AddDays( 1).Date.ToString("yyyy-MM-dd"   "T08:30")" 
  max="2025-12-30T16:30" 
  value="@DateTime.Now.AddDays( 2).Date.ToString("yyyy-MM-dd"   "T09:00")"
  />
  • Related