I'm using the following code to check if a valid date has been typed into a textbox:
public bool ValidateDate(Control ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Text))
{
DateTime value;
if (!DateTime.TryParse(ctrl.Text, out value))
{
return false;
}
}
return true;
}
private void txtStartDate_Validating(object sender, CancelEventArgs e)
{
if (Utils.ValidateDate(txtStartDate))
{
errorProvider.SetError(txtStartDate, "");
}
else
{
errorProvider.SetError(txtStartDate, "* Invalid Date");
e.Cancel = true;
}
}
This works fine for dates that are entered m/d/yy, m/d/yyyy, mm/dd/yy, mm/dd/yyyy. If a user enters in a date such as "11/17" this will evaluate to a valid date, but, unfortunately, I only want dates that have all three date parts.
Is there an easy way to do this? I was thinking something a long the lines of checking if there are 2 "/" in the textbox, but I'm sure there is a cleaner way of achieving the desired result.
EDIT: Thanks for all the suggestions everyone! I ended up using the following code which accepts M/d/yyyy and M/d/yy ~
public bool ValidateDate(Control ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Text))
{
string[] formats = {"M/d/yyyy", "M/d/yy"};
DateTime value;
if (!DateTime.TryParseExact(ctrl.Text, formats, new CultureInfo("en-US"), DateTimeStyles.None, out value))
{
return false;
}
}
return true;
}