Anyone got a Date of Birth Validation Attribute fo

2019-05-01 06:46发布

Someone must have written this before :-)

I need a validation attribute for date of birth that checks if the date is within a specific range - i.e. the user hasn't inputted a date that hasn't yet happened or is 150 years in the past.

Thanks for any pointers!

1条回答
何必那么认真
2楼-- · 2019-05-01 07:22
[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);
    }
}

You could use the built-in Range attribute:

[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; }

查看更多
登录 后发表回答