任何人都有C#MVC的出生日期验证属性?

bee*_*bul 5 c# validation model-view-controller attributes

有人必须在此之前写过:-)

我需要一个出生日期的验证属性来检查日期是否在特定范围内 - 即用户尚未输入尚未发生的日期或过去150年.

感谢您的任何指示!

Luk*_*keH 6

[DateOfBirth(MinAge = 0, MaxAge = 150)]
public DateTime DateOfBirth { get; set; }

// ...

public class DateOfBirthAttribute : ValidationAttribute
{
    public int MinAge { get; set; }
    public int MaxAge { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
            return true;

        var val = (DateTime)value;

        if (val.AddYears(MinAge) > DateTime.Now)
            return false;

        return (val.AddYears(MaxAge) > DateTime.Now);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用内置Range属性:

[Range(typeof(DateTime),
       DateTime.Now.AddYears(-150).ToString("yyyy-MM-dd"),
       DateTime.Now.ToString("yyyy-MM-dd"),
       ErrorMessage = "Date of birth must be sane!")]
public DateTime DateOfBirth { get; set; }
Run Code Online (Sandbox Code Playgroud)