0

我需要正则表达式来验证日期格式ddmmyy

4

1 回答 1

0

K,我将继续假设您还需要验证它是否是有效日期。所以......这样做:

<asp:TextBox id="txtDate" runat="server" MaxLength="6" />
<asp:CustomValidator runat="server" ControlToValidate="txtDate" OnServerValidate="validate_Date" ErrorMessage="Invalid (ddmmyy)" />

后面的代码:

protected void validate_Date(object sender, ServerValidateEventArgs args)
{
    System.Text.RegularExpressions.Regex rDate = new System.Text.RegularExpressions.Regex(@"^(?<day>[0-9]{2})(?<mon>[0-9]{2})(?<year>[0-9]{2})");
    System.Text.RegularExpressions.Match m = rDate.Match(args.Value);
    if (m.Success)
    {
        //Now try parse as a date
        DateTime dtCheck = DateTime.MinValue;
        args.IsValid = DateTime.TryParse(String.Format("20{0}-{1}-{2}", m.Groups["year"].Value, m.Groups["mon"].Value, m.Groups["year"].Value), out dtCheck);
    }
}
于 2012-10-05T06:42:30.367 回答