简体   繁体   中英

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

在此处输入图片说明

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).

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM