How can I use asp validation to validate the range of date input in C#?

48 Views Asked by At

I am trying to validate my date input field with asp-validation, but I keep getting this type of error Error_Image

This is what I did in my Model:

 public static readonly DateTime MinDate = new DateTime(2000, 01, 01);
        public static readonly DateTime MaxDate = DateTime.Now.AddMonths(-4);

        [Display(Name = "Date of Birth:")]
        [Range(typeof(DateTime), nameof(MinDate), nameof(MaxDate), ErrorMessage = "Date must be between January 1, 2000 and 4 months from now.")]

I tried to simply type the date as strings to see if my code runs properly and it does.

[Range(typeof(DateTime), "01/01/2000", "02/06/2022", ErrorMessage = "Date must be between January 1, 2000 and 4 months from now.")]

I believe the way I am using the DateTime object is wrong, although I can't figure out what the issue is exactly.

1

There are 1 best solutions below

0
Serge On

The problem is that attributes accept only constants as parameters. DateTime object can not be a constant. But you can create a custom attribute

    [Display(Name = "Date of Birth:")]
    [RangeDateAttribute( ErrorMessage = "Date must be between January 1, 2000 and 4 months from now.")]
    public DateTime DOB { get; set; }

public class RangeDateAttribute : RangeAttribute
{
    public RangeDateAttribute()
      : base(typeof(DateTime),
              new DateTime(2000, 01, 01).ToShortDateString(),
               DateTime.Now.AddMonths(-4).ToShortDateString())
    { }
}