Home > Back-end >  Setting a minimum date input value
Setting a minimum date input value

Time:01-28

My Razor Pages application has a modal form that allows the user to enter the date. And I bind this to a property in my model.

[BindProperty]
public DateTime? TripDate { get; set; }

Two questions:

  1. Is it possible to set a minimum valid value?
  2. Is it possible to change this minimum valid value from JavaScript/jQuery at run time?

I want to set a different minimum value depending on which date is being entered. But I could also set the minimum value from the server side if that's easier.

CodePudding user response:

Yes, it is possible to set a minimum valid value for a date input in a Razor Pages application.

  1. To set a minimum valid value for the date input, you can use the min attribute on the input element. For example, if you want to set the minimum date to January 1, 2020, you can use the following code in your Razor template:

input

<input asp-for="TripDate" min="2020-01-01" />

2.It is also possible to change the minimum valid value from JavaScript/jQuery at runtime. You can use the jQuery attr function to set the min attribute to a new value. For example, to set the minimum date to the current date:

$('input[asp-for="TripDate"]').attr('min', new Date().toISOString().split('T')[0]);

If you want to set the minimum value based on the entered date you can use the same logic and manipulate it as per your requirement. You can also use the server side logic to validate and set the minimum value based on your requirement. It is recommended to validate the date on both client and server side to ensure the data integrity.

  • Related