Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validate date 1

Status
Not open for further replies.

lfc77

Programmer
Aug 12, 2003
218
GB
I've seen a lot of complicated ways of finding out whether a date is valid or not. I have a textbox which has no user input validation and I am trying to convert the valid entered in it into a date, in order to test whether or not the date is valid.

It seems to work so far, but I wondered if it is advisable to do it this way? My code is below:

try
{
DateTime DateFrom = Convert.ToDateTime(txtDateFrom.Text);
}
catch
{
lblLogResult.Text += "Invalid Date From";
}


Thanks,

Mike
 
I think it is the right way to do it.

You could also write a general function (which you would put in a utility class, i.e. Utils) for it like this:

Code:
public static bool IsDateTime(string value)
{
    try {
        Convert.ToDateTime(value);
        return true;
    }
    catch {
        return false;
    }
}

and then your code would look like this:

Code:
if (Utils.IsDateTime(txtDateFrom.Text))
{
    DateTime DateFrom = Convert.ToDateTime(txtDateFrom.Text);
}
else
{
    lblLogResult.Text += "Invalid Date From";
}

regards,
Blaxo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top