我用下面的代码来检查有效日期已经被输入到一个文本框:验证日期文本框
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;
}
}
这工作正常对于被输入米日期/ d/YY,M/d/yyyy,mm/dd/yy,mm/dd/yyyy。如果用户输入诸如“11/17”之类的日期,则这将评估为有效日期,但不幸的是,我只希望具有全部三个日期部分的日期。
有没有简单的方法来做到这一点?我在想如果检查文本框中是否有2个“/”,我想了很长的一段时间,但我确信有一个更清晰的方法来实现所需的结果。
编辑:谢谢大家的所有建议!我结束了使用下面的代码,它接受M/d/yyyy的和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;
}
不错。我完全忘记了TryParseExact。从我+1。 – 2009-11-18 00:19:40
DateTime.TryParseExact()具有覆盖以接受多种格式,因此我不必放弃格式灵活性。谢谢! – Sesame 2009-11-18 00:46:35
优秀。我忘记了那个过载。我很高兴为你工作。 – 2009-11-18 01:03:31