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>


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

4 comments:

Anonymous said...

The working reg ex is:

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

Fabrício Rissetto said...

/\ This work in c#

Fabrício Rissetto said...

ops...
This works in c# \/

Fabrício Rissetto said...

ops...
This works in c# \/

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