Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyone got a Date of Birth Validation Attribute for C# MVC?

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!

like image 709
beebul Avatar asked Jul 22 '10 14:07

beebul


2 Answers

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

like image 59
LukeH Avatar answered Sep 23 '22 02:09

LukeH


I made a Validate class where I can validate data. In my class I have 2 methods for validating date of birth: 1 that takes a string parameter and the other takes a date parameter. Here is the basic method:

public static bool DateOfBirthDate(DateTime dtDOB) //assumes a valid date string
{
    int age = GetAge(dtDOB);
    if (age < 0 || age > 150) { return false; }
    return true;
}

Here is the full class:

using System;
using System.Collections.Generic;
using System.Text;

namespace YourNamespaceHere
{
    public class Validate
    {
        public static bool DateOfBirthString(string dob) //assumes a valid date string
        {
            DateTime dtDOB = DateTime.Parse(dob);
            return DateOfBirthDate(dtDOB);
        }

        public static bool DateOfBirthDate(DateTime dtDOB) //assumes a valid date
        {
            int age = GetAge(dtDOB);
            if (age < 0 || age > 150) { return false; }
            return true;
        }

        public static int GetAge(DateTime birthDate)
        {
            DateTime today = DateTime.Now;
            int age = today.Year - birthDate.Year;
            if (today.Month < birthDate.Month || (today.Month == birthDate.Month && today.Day < birthDate.Day)) { age--; }
            return age;
        }

    }
}

Here is how I'm calling the method in my Xamarin.Forms app:

bool valid = Validate.DateOfBirthDate(pickerDOB.Date);

Where pickerDOB is a date picker on my form. This makes it easy to call the validation methods from anywhere and validate a string or DateTime object.

like image 43
SendETHToThisAddress Avatar answered Sep 23 '22 02:09

SendETHToThisAddress