在任何日期格式的TextBox上使用正则表达式

时间:2014-11-01 22:55:56

标签: c# asp.net regex

我希望能够实现这一目标,但接受任何格式:01/01/2001或01-01-2001或01-01-2001。有任何想法吗?

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack = "true" CausesValidation = "true">     </asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate = "TextBox1"
ValidationExpression = "^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$"// anyway i can add or here with other regex requirements
runat="server" ErrorMessage="Invalid Date format. Valid Date Format see above">
</asp:RegularExpressionValidator>

1 个答案:

答案 0 :(得分:0)

您可以使用DateTime.TryParse通过DateTime验证CustomValidator

protected void ValidateDate(Object sender, ServerValidateEventArgs e)
{ 
    string[] allowedFormats = { "dd/MM/yyyy","dd-MM-yyyy", "dd-MM-yyyy" };
    DateTime dt;
    e.IsValid = DateTime.TryParseExact(e.Value, allowedFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
}

ASPX:

<asp:CustomValidator ID="ValidDate" ControlToValidate="TextBox1" OnServerValidate="ValidateDate" runat="server"></asp:CustomValidator>