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