Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Age Not Under 18

How to show a error message if the person is under 18 years old? I use the following code, but it always displays that the age is invalid, even if I enter a date earlier than 1995.

DateTime dt = DateTime.Parse(dob_main.Text);
DateTime dt_now = DateTime.Now;

DateTime dt_18 = dt.AddYears(-18);

if (dt.Date >= dt_18.Date)
{
    MessageBox.Show("Invalid Birth Day");
}
like image 537
Adax Avatar asked Aug 13 '26 15:08

Adax


1 Answers

You should try something along:

var age = GetAge(dt);
if(age < 18)
{
    MessageBox.Show("Invalid Birth Day");
}

int GetAge(DateTime bornDate)
{
    DateTime today = DateTime.Today;
    int age = today.Year - bornDate.Year;
    if (bornDate > today.AddYears(-age)) 
        age--;

    return age;
}

Offtopic note: consider naming your variables in such a way, that SO users can guess what is the intention of that variable by reading it. dt dob_main and dt_18 are far away from being good names.

like image 148
Ilya Ivanov Avatar answered Aug 16 '26 08:08

Ilya Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!