How to Validate a given Date in C#


In this article I explain about How to Validate a given Date in C#

This example method shows you how to validate a given date using C#.

// Method to validate a string against date
// Input : a string containing date
// Output : true if the string contains date; otherwise false



public bool ValidateDate(string val)
{

int year=0;
int month=0;
int day = 0;
string[] date;

try
{
date = val.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);

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




Comments

Author: nam23 Oct 2010 Member Level: Bronze   Points : 1

This function is wrong because how to check if a month don't have 31th day (only 1..30) or some year with Fer without 29th (only 1..28). Example: 31/09/2010 or 29/02/2010.
We can use simple function tho check date like this:
public bool ValidateDate(string val)
{

int year=0;
int month=0;
int day = 0;
string[] date;

try
{
date = val.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);
}

Author: sugaur01 Nov 2010 Member Level: Bronze   Points : 1

how to get date from the textbox and assign to val..if this coding is use on form..

Author: Danu J Nair01 Nov 2010 Member Level: Silver   Points : 1

Hi sugaur,

Just get the value from the text box and pass it to the function

bool IsValidDate=ValidateDate(textboxid.text);

Regards,
Danu



  • 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: