Has anyone got a date attribute for C # MVC?

Someone should have written this before :-)

I need a validation attribute for a date of birth, which checks if the date is in a certain range - that is, the user has not entered a date that has not yet occurred, or has 150 years in the past.

Thanks for any pointers!

+5
source share
1 answer
[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 can use the built-in attribute 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; }

Strike>

+6
source

All Articles