views:

70

answers:

1

I'm having some difficulty understanding how to validate a date (DOB) using MVC2. What I want to do is 1. Is the date entered a valid date and, 2. Is the date at lease 13 years in the past. For example, to validate an email I use the following code:

[Required(ErrorMessage = "Email address is required.")]  
[StringLength(320, ErrorMessage = "Email must be less than 320 characters.")]  
[Email(ErrorMessage = "This email address is invalid.")]  
public string email { get; set; }  

To validate the email I use:

public class EmailAttribute : RegularExpressionAttribute
{        
    public EmailAttribute()
        : base("insert long regex expression here") { }
}

Any assistance would be greatly appreciated, thanks!

+1  A: 

Try this:

public class YearsInThePast : RangeAttribute
{
    public YearsInThePast(int yearsInThePast) : base(
        typeof(DateTime), 
        DateTime.MinValue.ToString(), 
        DateTime.Now.AddYears(-yearsInThePast).ToString()
    )
    { }
}

And your model:

public class MyModel
{
    [YearsInThePast(13, ErrorMessage = "Date must be 13 years in the past")]
    public DateTime Date { get; set; }
}
Darin Dimitrov
That did the trick. Thanks for the help!
Andy Evans