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:

  1. I was looking for this. Thanks for posting.

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

    ReplyDelete
  3. yes it is :)

    ReplyDelete
  4. 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])

    ReplyDelete
  5. Bonjour! Phillip Swanson . payday loans

    ReplyDelete
  6. Doesnt work.. tried it with 09:00

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

    ReplyDelete
  8. Works well with the update.

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

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

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

    ReplyDelete

Note: Only a member of this blog may post a comment.