views:

18

answers:

1

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
@Andrew, I will use a generic age calculation instead of based on days.
Syd