The program im writing currently I need to check if the year given by the user is within a certain range. The bottom value is a fixed value, but the top of this range should be capped at the current year and update itself whenever we enter a new year. I have tried using DateTime.Now.Year assigned to an int value for comparison, but range can't compare non static values.
[Range(1900, 2022, ErrorMessage = "Property built before 1900.")]
Above is the line in question. Any advice?
CodePudding user response:
You can't do this with an attribute. Attributes must use constant values. You could either validate the data within the method or just use a minimum value (since that seems to be a constant.
CodePudding user response:
You can't use RangeAttribute
for this task as it only works with constant values for min/max.
But you can make custom validation attribute for this task. Something like
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class YearRangeAttribute : RangeAttribute
{
public YearRangeAttribute(int minimum) : base(minimum, DateTime.Now.Year)
{
}
}
Here we hide the maximum
value from constructor and internally set it to the current year. In other aspects our new attribute works as a normal RangeAttribute
.
The problem here is that is maximimum
is fixed at the moment when attribute instance is created. So, if you start a program at Dec 31, then you will have a problem after 24 hours of runtime as the real year will be changed, but your maximum
will not.
Unfortunately, the Maximum
property of RangeAttribute
is not virtual so you can't override it.
This problem may be solved with custom attribte not inhernited from RangeAttribute
, but from ValidationAttribute
. Then you can reimplement the logic of RangeAttribute
(sources available here). You can throw out the most part of reference implementation and implement all logic only for int
.