Validating Time in ASP.NET using a Regular Expression

In one of the forums, I came across a question where a user wanted to validate time in ASP.NET. The requirements were the following:

- Acceptable values were 23:59, 00:00, 23 (equivalent to 23:00) and so on

- Values to be disallowed were 24:00, 23:5, 23:0 and so on

Here’s the regex shared by RQuadlin to achieve this requirement.

^([ 01]?[0-9]2[0-3])(:([0-5][0-9]))?$

In an ASP.NET scenario, we will be using a Regular Expression Validator to validate time. The markup will look similar to the following:

<div>
<
asp:TextBox ID="txtTime" runat="server">
</
asp:TextBox>
<
asp:RegularExpressionValidator ID="rev"
runat="server" ErrorMessage="InvalidTime" ControlToValidate="txtTime"
ValidationExpression="^([ 01]?[0-9]2[0-3])(:([0-5][0-9]))?$">
</
asp:RegularExpressionValidator>
</
div>

4 comments:

  1. The working reg ex is:

    ^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$

    ReplyDelete
  2. Fabrício RissettoJuly 7, 2011 at 7:40 AM

    /\ This work in c#

    ReplyDelete
  3. Fabrício RissettoJuly 7, 2011 at 7:42 AM

    ops...
    This works in c# \/

    ReplyDelete
  4. Fabrício RissettoJuly 7, 2011 at 7:43 AM

    ops...
    This works in c# \/

    ValidationExpression="(([01][0-9])|(2[0-3])):([0-5][0-9])$"

    ReplyDelete