Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

c# - Is there a RangeAttribute for DateTime?

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 tried using range like

[Range(DateTime.Now.AddYears(-6), DateTime.Now)]
public DateTime Datetim { get; set; }

But this throws an error cannot convert system datetime to double. Can anyone suggest a workaround to this in the model itself?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...