Search code examples
asp.net-mvcvalidationdatetimeupdate-attributes

Using MVC2, how do I validate that a date is within a given date range?


I have a requirement, in an MVC2 web application, to validate that the user is at least 13 years old. Is there a date/datetime validation attribute that will enable me to do this?


Solution

  • Since you're not "really" validating a date, you're validating based an equation (Today - Date > 13), you'll probably have to write a custom validation attribute. Something like this (this is just a back-of-the-napkin example).

    using System.ComponentModel.DataAnnotations;
    public class AgeValidationAttribute : ValidationAttribute
        {
            public int MinAge { get; set; }
    
            public override bool IsValid(DateTime value)
            {
                if (value == null)
                {
                    return true;
                }
    
                return DateTime.Now.Subtract(value).TotalDays > (MinAge * 365.25);
            }
        }