DateTimeRangeValidatorAttribute: how to send a DateTime param?

Topics: Validation Application Block
Aug 25, 2010 at 9:43 PM

Here is DateTimeRangeValidatorAttribute definition:

public DateTimeRangeValidatorAttribute(System.DateTime lowerBound, System.DateTime upperBound)
    Member of Microsoft.Practices.EnterpriseLibrary.Validation.Validators.DateTimeRangeValidatorAttribute

Here is how I use that validation attribute:

        [DateTimeRangeValidator(xxx, xxx)]
        public DateTime ValueReferDate { get; set; } // the date I want to validate

If I use DateTime.Now or DateTime.Parse("some date here") for xxx, I got compile-time error "an attribute argument must be a constant expression".

I know there are overloaded constructors taking a string instead of a date, but in my case I need (current year + 1) to be the upper bound date.

So, my question is: how to make a constant expression of DateTime type and is it even possible?




Aug 26, 2010 at 4:14 AM

As far as I know you can't have a constant DateTime in C#. Though, I've seen this article discussing an approach on how to achieve dynamic attribute parameters utilizing the TypeDescriptor class (personally I haven't tried this one yet). Hope this may help. 

Btw, is using something like

DateTimeRangeValidator("1899-01-01T00:00:00", "1999-01-01T00:00:00")]

would not work for you?

Gino Terrado
Global Technology and Solutions
Avanade, Inc.

Aug 26, 2010 at 6:44 PM

Thank you Gino for the link to TypeDescriptor article, but having to write 3 pages of code for a single simple validation I think defeats the purpose of attributes.

As I indicated in my post, my upper bound needs to be (current year + 1), so static string won't do.

Looks like I am left with custom SelfValidator.