开发者

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

开发者 https://www.devze.com 2023-01-03 18:56 出处:网络
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?Since y

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?


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);
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号