views:

703

answers:

3

Hi

Is it possible to use [Range] annotation for dates?

something like

[Range(typeof(DateTime), DateTime.MinValue.ToString(), DateTime.Today.ToString())]

Thanks

Davy

A: 

Docs on MSDN says you can use the RangeAttribute

[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
        ErrorMessage = "Value for {0} must be between {1} and {2}")]
public datetime Something { get; set;}

Kindness,

Dan

Daniel Elliott
Thanks Dan - I get an error though and not sure how to fix:'System.ComponentModel.DataAnnotations.RangeAttribute' does not contain a constructor that takes '0' argumentsany idea?
Davy
Thanks for all your help Dan - That seems to work but I can't substitue theh hardcodes strings for something like DateTime.Now.Date.toString() I get:An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter typeSry - I'm probably doing something dumb :)Davy
Davy
+1  A: 

I did this to fix your problem

 public class DateAttribute : RangeAttribute
   {
      public DateAttribute()
        : base(typeof(DateTime), DateTime.Now.AddYears(-20).ToShortDateString(),     DateTime.Now.AddYears(2).ToShortDateString()) { } 
   }
Hurricanepkt
A: 

Anyone got the previous DateAttribute working?

I have a similar need but I can't make this work:

public class YearRangeAttribute : RangeAttribute
    {
        public YearRangeAttribute()
            : base(typeof(DateTime), DateTime.Now.AddYears(-100).Year.ToString(), DateTime.Now.AddYears(-14).Year.ToString()) { }

    }

There is nothing on the page when it is rendered to the browser.

Any ideas?

TIA

Lizet