Here I will show you how to set date input field's min date to today by Tag Helper in asp.net core.
Create a new class name it InputDateTagHelper (or any name you like it).
Update the InputDateTagHelper.cs class with the following code statements:
[HtmlTargetElement("input", Attributes ="is-accept-old-day")] public class InputDateTagHelper : TagHelper { [HtmlAttributeName("is-accept-old-day")] public bool OldDay { get; set; } = false; public override void Process(TagHelperContext context, TagHelperOutput output) { if (!OldDay) { var dateTime = DateTime.Now; var dd = dateTime.Day; var mm = dateTime.Month; var yyyy = dateTime.Year; string newDay = Convert.ToString(dd); string newMonth = Convert.ToString(mm); if (dd < 10) { newDay = $"0{newDay}"; } if(mm < 10) { newMonth = $"0{mm}"; } var today = $"{yyyy}-{newMonth}-{newDay}"; output.Attributes.SetAttribute("min", today); } } }
The previous code is accept a boolean field OldDay if the field is false then set a min attribute to Date Input field and set it's value to date of today.
To test this new tag helper in your .cshtml file, you have to register it inside _ViewImport.cshtml file first, Here is the code:
@addTagHelper Platform.Infrastructure.*, Platform
The Platform is my ProjectName and the Infrastructure is the folder that I put the InputDateTagHelper.cs class inside it
So, now you can use the InputDateTagHelper like so:
<input type="date" is-accept-old-day="false" />
Here I force the input field to accept the today as a min date by passing false to is-accept-old-day field
The HTML output is
<input type="date" min="2021-08-13">
Top comments (0)