Ajay
Ajay

Reputation: 6590

MVC date range between min and max value

I am trying to add a range for date in my model.

I have added following property to my class

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Date Schedule")]
    [Range(typeof(DateTime), DateTime.Now.ToString("dd/MM/yyyy"), DateTime.Now.AddDays(120).ToString("dd/MM/yyyy"), ErrorMessage = "Please select valid date")]
    public DateTime? DateSchedule { get; set; }

It gives me following error

enter image description here

How can I assign Min and Max value to my DateSchedule? In calendar control it should only display date from today to 120 days(In my class I have added 120 days).

Upvotes: 0

Views: 1861

Answers (1)

Neel
Neel

Reputation: 11721

Attributes accept only constants as parameters.

We know that DateTime.Now isn't a constant, it changes depending on when the code runs. and Range attribute is determined at compile time.

You need to create custom validator as shown below :-

public class DateAttribute : RangeAttribute
{
    ////your code
}

Upvotes: 1

Related Questions