开发者

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?


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜