Is there a RangeAttribute for DateTime?

后端 未结 3 1313
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 15:57

I have a Datetime field in my Model and need to validate it so that when it is created it has to fall between Now and 6 Years Prior. I have

3条回答
  •  萌比男神i
    2020-12-01 16:39

    Even though there is an overload for Range attribute that accepts type and boundary values of that type and allows something like this:

    [Range(typeof(DateTime), "1/1/2011", "1/1/2012", ErrorMessage="Date is out of Range")]
    

    what you are trying to achieve is not possible using this attribute. The problem is that attributes accept only constants as parameters. Obviously neither DateTime.Now nor DateTime.Now.AddYears(-6) are constants.

    However you can still do this creating your own validation attribute:

    public class DateTimeRangeAttribute : ValidationAttribute
    {
        //implementation
    }
    

提交回复
热议问题