如何检查输入的日期是否格式正确?

时间:2011-04-29 14:28:30

标签: vb.net winforms

我有一个文本框,用户应该输入日期。如何检查输入的日期是否采用正确的日期格式?

  

像这样:02/02/2008

  • 不喜欢这个022/22/-1
  • 不喜欢这个2009/02/02
  • 不喜欢这个02/Jun/2015
  • 不喜欢这个02/abc/2010

(我不想使用DateTimePicker或MonthCalender)。

编辑1

我试过这样的

Private Sub txtHireDate_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtHireDate.Validated
    Dim dateString As String = txtHireDate.Text
    Dim formats As String = "MM/dd/yyyy"
    Dim dateValue As DateTime

    If DateTime.TryParseExact(dateString, formats, New CultureInfo("en-US"), DateTimeStyles.None, dateValue) Then

    End If

但它显示出一些错误

enter image description here

2 个答案:

答案 0 :(得分:6)

使用DateTime.TryParseExact功能:

String dateString = dateTextBox.Text;
String formats = "MM/dd/yyyy";
DateTime dateValue;

if (DateTime.TryParseExact(dateString, formats, 
                              new CultureInfo("en-US"), 
                              DateTimeStyles.None, 
                              out dateValue))
{
    // That means the value of the date is in the specified format..
}

别忘了使用Globalization namespace

using System.Globalization;

答案 1 :(得分:2)

我在文本框下的FormatValidator控件中使用以下正则表达式:

^(19|20)\d\d[- /.]?(0[1-9]|1[012])[- /.]?(0[1-9]|[12][0-9]|3[01])$

这是以年 - 月 - 日格式,并允许以下格式:

  • YYYY-MM-DD
  • YYYYMMDD
  • YYYY / MM / DD
  • YYYY.MM.DD

请注意,使用标准北美日期时,不能混淆年月日格式。美国格式(MM / dd / yyyy)将以不同于加拿大格式(dd / MM / yyyy)的方式进行解析,但在达到高于12的天数之前,你不会知道这是错误的......

向页面添加验证器的示例:

<asp:RegularExpressionValidator ID="txtTreatmentDate_FormatValidator" runat="server" 
    Display="Dynamic" ValidationGroup="LogSave"
    ControlToValidate="txtTreatmentDate" ValidationExpression="ThisIsIgnored"
    ErrorMessage="*Invalid Date" />

然后在你的代码背后(C#)

protected void Page_Load(object sender, EventArgs e)
{
    txtTreatmentDate_FormatValidator.ValidationExpression = DateHandler.DateFormatStandardRegex;
}

在DateHandler中(如果需要,还有时间格式):

public static readonly String DateFormatStandardRegex = "^(19|20)\\d\\d[- /.]?(0[1-9]|1[012])[- /.]?(0[1-9]|[12][0-9]|3[01])$";
public static readonly String TimeFormat24HourRegexp = "(20|21|22|23|[01]\\d):?([0-5]\\d):?([0-5]\\d(\\.\\d*)?)?";

由于你没有指定你正在寻找的格式(我假设是美国),我没有修改它为你工作,但是移动块并改变允许的分隔符是一件简单的事。

加拿大格式:

"^(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\\d\\d$";

在解析日期时,您肯定希望将ParseExact与EN-CA(我认为这是简短格式)文化一起使用,或指定您希望日期符合的格式字符串(即“dd / MM / yyyy” “)