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?
A:
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);
}
}
Andrew Lewis
2010-06-18 15:12:45
@Andrew, I will use a generic age calculation instead of based on days.
Syd
2010-06-18 22:58:35