RegularExpression to validate Time in 12 Hour format in ASP.Net

Last Reply 3 months ago By arunkurmi

Posted 3 months ago

This expression works perfectly on many online regex test sites.

(1[0-2]|0[1-9]):([0-5][0-9])(\s*)(i?[AP]M)?

against this string, which is in a textbox.

01:30 AM

The textbox is a simple textbox. The string value has been thoroughly screened for extra spaces or whatever. It is simple '01:30 AM'

The regex control on my page fails. Many alterations attempted but this should work. There are no errors on the page at allout

Can anyone see the issue? Or know of a know bug?

Thank you,

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
    ErrorMessage="***" ControlToValidate="TextBox2"
    Display="Dynamic" ForeColor="Red" SetFocusOnError="true"
    ValidationExpression="^(1[0-2]|0[1-9]):([0-5][0-9])(\s*)(i?[AP]M])$">
</asp:RegularExpressionValidator>
<asp:TextBox ID="TextBox2" runat="server" Text="01:30 AM"  ></asp:TextBox>
Posted 3 months ago

Hi ECSMOORE,

Please use this regular expression for time.

regular expression- "((1[0-2]|0?[0-9]):([0-5][0-9]) ?([AaPp][Mm]))"

Sample

<asp:TextBox runat="server" ID="txtTime" Text="01:30 AM" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid Time"
    ControlToValidate="txtTime" Display="Dynamic" ForeColor="Red" SetFocusOnError="True"
    ValidationExpression="((1[0-2]|0?[0-9]):([0-5][0-9]) ?([AaPp][Mm]))"></asp:RegularExpressionValidator>

Screenshot