Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate valid time

Tags:

c#

.net

regex

I need a regular expression to validate time.

Valid values would be from 0:00 to 23:59.

When the time is less than 10:00 it should also support one character numbers.

These are valid values:

  • 9:00
  • 09:00
like image 863
juan Avatar asked May 19 '09 20:05

juan


People also ask

How does regular expression validate time in 12-hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

How do you validate a regular expression?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.


2 Answers

Try this regular expression:

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

Or to be more distinct:

^(?:0?[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
like image 161
Gumbo Avatar answered Oct 14 '22 06:10

Gumbo


I don't want to steal anyone's hard work but this is exactly what you're looking for, apparently.

using System.Text.RegularExpressions;

public bool IsValidTime(string thetime)
{
    Regex checktime =
        new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");

    return checktime.IsMatch(thetime);
}
like image 27
Nick Presta Avatar answered Oct 14 '22 07:10

Nick Presta