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>





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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])$"