Sponsored Ad

Monday, March 22, 2010

Check Date of Birth Validity | Validate DOB in C#

       Here is a utility to get if age is valid against minimum allowed age. We have to pass date of birth and minimum allowed age as a parameter and it will check and return the true if  DOB is valid and false if invalid.

 

       /// <summary>
       /// Validate date of birth.
       /// </summary>
       public static bool IsValidAge(DateTime DOB, int minAllowedAge)
       {
           int AllowedAge;
           AllowedAge = DateTime.Now.Year - DOB.Year;

           if (AllowedAge < minAllowedAge)
           {
               return false;
           }

           if (DOB.Year < DateTime.Now.Year)
           {
               return true;
           }

           return false;
       }

2 comments:

  1. This is my code to validate a DOB but I keep on getting same result when I put a person whose older than 18 and it not suppose to be like that. Help will be appreciated


    DateTime DateOfBirth = DateTime.Parse("1993, 12, 31");

    if (DateOfBirth >= DateTime.Now.AddYears(-18))

    Response.Write("ID Correct");
    else

    if (DateOfBirth <= DateTime.Now.AddYears(-19))
    {
    Response.Write("you are older than 18");
    }

    ReplyDelete
  2. Hi Just change you code like below

    DateTime DateOfBirth = DateTime.Parse("1993, 12, 31");

    if (DateOfBirth >= DateTime.Now.AddYears(-18))

    Response.Write("ID Correct");
    else
    {
    Response.Write("you are older than 18");
    }

    now it will show different message for different date of birth.

    try with DateTime.Parse("1993, 12, 31"); //will show "id correct"

    DateTime.Parse("1993, 1, 31"); //will show "you are older than 18".

    Let me know if you face any other problem

    ReplyDelete

Sponsored Ad

Website Update

Followers