2014-11-01 57 views
0

我希望能够完成此操作,但接受任何格式: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> 
+0

你想要什么格式的日期是?你想接受任何日期格式或只是一个特定的格式? – mwilson 2014-11-01 22:59:17

回答

0

你可以使用DateTime.TryParse验证DateTimeCustomValidator

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>