Setting minimum and maximum date range to DateTime input

Viewed 1826

Is there a way to set a range for DateTime in the View Model, in a way that makes the maximum possible date one can input be the current date and time (UTC), and the minimum date possible be a year ago?

Something like [Range(typeof(DateTime), "06/06/2020 23:43", "Utc.Now")]?

Thank you in advance.

2 Answers

If you want to validate the DateTime range on server-side, you would define a custom attribute to validate your property value.

    public class ValidateDate: ValidationAttribute
    {
        protected override ValidationResult IsValid
                         (object date, ValidationContext validationContext)
        { 
             return (date<= DateTime.Now && date >= DateTime.Now.AddYears(-1))
                 ? ValidationResult.Success
                 : new ValidationResult("Invalid date range"); 
        }
    }

And your property should be decorated with the attribute

[ValidateDate]
public DateTime MyDate{get; set;}

If you want to restrict user input, you can set the following settings on your view.

<input asp-for="SelectedDate" max="@DateTime.Now.ToString("yyyy-MM-ddThh:mm")" min="@DateTime.Now.AddYears(-1).ToString("yyyy-MM-ddThh:mm")" />

Result: enter image description here

Related