Validation for Date of birth


I found that many applications use Textboxes to get Date Of Birth instead of Calendar. This resource explains you as how to validate the date of birth if the user enters the date of birth in TextBox instead of calendar.

Learn Validation for Date of birth in Textbox


The date of Birth if entered in TextBoxes rather than Calendar you can use my below function to validate the date of birth.

This function may reduce your burden of validation of Date Of Birth.

Just copy and paste my below function in your code



public bool ValidateDate(string Date)
{
int year = 0;
int month = 0;
int day = 0;
string[] date;
try
{
if (Convert.ToDateTime(Date) > DateTime.Now)
{
return (false);
}
date = Date.Split('/');

if (date.Length != 3)
return (false);

day = int.Parse(date[0]);
month = int.Parse(date[1]);
year = int.Parse(date[2]);

if (!(year >= 0 && year <= 9999))
return (false);
if (!(month >= 01 && month <= 12))
return (false);
if (!(day >= 01 && day <= 31))
return (false);

DateTime d = new DateTime(year, month, day);//If it can't convert to date will happend exeption & return false

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return (false);
}
return (true);
}



Here the Date is the Date Of Birth input given by user.
I have used the date format as "dd/mm/yyyy". If your format changes you need to change the


day = int.Parse(date[0]);
month = int.Parse(date[1]);
year = int.Parse(date[2]);


values as per your format.

Thus by this you can validate the Date Of Birth textboxes easily.
It also checks for number of days for each month(Eg: February has 28 (or) 29 days)

Enjoy coding


Regards,
S.Rajeswari
Steadfast Technology


Comments

Author: chandra09 Aug 2011 Member Level: Silver   Points : 0

thanq and this will be useful for us

Author: Suresh09 Sep 2011 Member Level: Gold   Points : 1

Hi Rajeswari,

It is Excellent Article about Validation for Date of birth.

This is great work. keep it up.

Regards
S.Suresh

Author: Rajeswari10 Sep 2011 Member Level: Silver   Points : 0

Hi ,
Thanks chandra and Suresh.

Author: Roshan R Mhatre14 Nov 2011 Member Level: Silver   Points : 0

This is Excelent Article but one thing is remaining
to validate birthdate is not greater than todays date.

Author: Rajeswari15 Nov 2011 Member Level: Silver   Points : 0

Hi Roshan,
I have updated the resource with the birthdate check with today's date. Thanks for your comment.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: