25 November 2008

C# Regex Time Validation With Regular Expression

In order to check whether an input is a valid time format or not,
regular expressions
can be used to validate the input value.

The sample function below show how to check if the input
is valid time in XX:XX, code is in C#.

This regular expression checks the input for 00:00 to 23:59 is a valid time format.

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);
}
Time regular expression used to control time is ^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$

Is valid time validation with regular expression in C#.

11 comments:

Anonymous said...

I was looking for this. Thanks for posting.

Anonymous said...

But does this work ?
At least for 12:00 ?? Joe

Anonymous said...

yes it is :)

Anonymous said...

This regular expression is not working for teh time format validation 00:00 to 23:59.

Hence I suggest you to use the following format:
(([0-1][0-9])|([2][0-3])):([0-5][0-9])

Anonymous said...

Bonjour! Phillip Swanson . payday loans

Anonymous said...

Doesnt work.. tried it with 09:00

Anonymous said...

(([0-1][0-9])|([2][0-3])):([0-5][0-9]) works.. thanks!

Michael said...

Works well with the update.

Anonymous said...

ValidationExpression="([01]\d|[2][0123]):[012345]\d"

Anonymous said...

Thanks Anonymous your code worked and make things easy for me.

n1y0 said...

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