Wednesday, January 13, 2010

Date Validation in C#

/// <summary>
/// Determine if Date String is an actual date
/// Date format = MM/DD/YYYY
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
private bool ValidateDate(string date)
{
try
{
// for US, alter to suit if splitting on hyphen, comma, etc.
string[] dateParts = date.Split('/');

// create new date from the parts; if this does not fail
// the method will return true and the date is valid
DateTime testDate = new
DateTime(Convert.ToInt32(dateParts[2]),
Convert.ToInt32(dateParts[0]),
Convert.ToInt32(dateParts[1]));

return true;
}
catch
{
// if a test date cannot be created, the
// method will return false
return false;
}
}

Source:: Easy Date Validation in C#
http://www.c-sharpcorner.com/UploadFile/scottlysle/DateValCS02222009225005PM/DateValCS.aspx


-------------------------------------------------------------------------
Date Validation:
try
{
departDate = DateTime.Parse(flightDepartureDateTextBox.Text);
}
catch (Exception ex)
{
feedbackLabel.Text = "Invalid data entry: " +
"Enter a valid date, for example: 02/02/2010";
return;
}

--------------------------------------------------------------------------
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

No comments: