Manoj Singh
Manoj Singh

Reputation: 7707

.NET Regular expression for time 24 hr format

Can I please have a regular expression in .NET, which will allow only 24 hr time format in the textbox.

Thanks.

Best Regards, MS

Upvotes: 4

Views: 9955

Answers (6)

Eugene Yokota
Eugene Yokota

Reputation: 95624

Regular Expressions: Time hh:mm validation 24 hours format:

([0-1]\d|2[0-3]):([0-5]\d)

If you need seconds too:

([0-1]\d|2[0-3]):([0-5]\d)(:([0-5]\d))?

Edit: To prevent trailing AM/PM, partial match can't be allowed or you have to put the expression between ^ and $.

^([0-1]\d|2[0-3]):([0-5]\d)(:([0-5]\d))?$

Upvotes: 11

Rad
Rad

Reputation: 8381

Personally, rather than go the validation route I would use a control like a datetime picker for the following reasons:

  • Zero validation is required. In fact the only validation you'd do would be business rules validation e.g. Order date cannot be later than today, etc
  • Easier on the user -- you don't have to tell the user to key in the time in 24 hour format

Upvotes: 1

AndersK
AndersK

Reputation: 36082

I would suggest you take a look at The Regulator for next time when you need a regular expression, its a great tool for designing your expressions.

Upvotes: 0

Vanilj
Vanilj

Reputation: 104

Try

^([0-1]?\d|2[0-3])(:[0-5]\d){1,2}$

Upvotes: 1

Taylor Leese
Taylor Leese

Reputation: 52320

What about using DatePicker or DateTimePicker depending upon if you're using WPF or Winforms? This might be a better UE anyways.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754763

Try this

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

It's 24 hour time with optional seconds. (Source)

Upvotes: 5

Related Questions