2

I am new in C#.net. I want a validation for textbox which take only hh:mm:ss format. Below is my code and its wroking. It gives output true 23:45:45 (example only) and also true for -23:45:45 (example only). Now I want validation which return false for -23:45:45 (example only) because it is negative time. My running code does not work for negative time.

          IsTrue = ValidateTime(txtTime.Text);
            if (!IsTrue)
            {

                strErrorMsg += "\nPlease insert valid alpha time in hh:mm:ss formats";
                isValidate = false;
            }

  public bool ValidateTime(string time)
    {
        try
        {
            Regex regExp = new Regex(@"(([0-1][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");

            return regExp.IsMatch(time);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

2 Answers 2

14

I wouldn't use regular expressions at all - I'd simply try to parse the result as a DateTime with a custom format:

public bool ValidateTime(string time)
{
    DateTime ignored;
    return DateTime.TryParseExact(time, "HH:mm:ss",
                                  CultureInfo.InvariantCulture, 
                                  DateTimeStyles.None,
                                  out ignored);
}

(If you really want to stick with regular expressions, follow the answer from Mels. And I'd get rid of the pointless try/catch block, and probably just construct the regex once and reuse it, too.)

5
  • Jon, woulnd't TimeSpan.TryParse be better ?
    – Habib
    May 6, 2013 at 7:29
  • Oh, nevermind, got my answer for negative hours :) +1. TimeSpan.TryParse would parse -23:45:45 as well.
    – Habib
    May 6, 2013 at 7:30
  • Out of curiosity: isn't there a more elegant way to indicate that we don't care about the actual parsed Date/Time? Other than using an ignored variable, that is?
    – Mels
    May 6, 2013 at 7:30
  • 1
    @Mels: Yes, you could use NodaTime and a LocalTimePattern, then just return ParseResult<LocalTime>.Success :) (It would still have parsed the time, but it's clearer what you're trying to do with it.)
    – Jon Skeet
    May 6, 2013 at 7:32
  • @Habib if you use custom format string as h\\:mm\\:ss, TimeSpan.TryParseExact will not parse -23:45:45
    – Jun Yu
    Oct 20, 2021 at 2:29
5

Surround your regex with ^ at the start and $ at the end. These mark the beginning and end of the string and invalidate the match when there are any other characters.

1
  • 6
    But yours has the benefit of explaining what was wrong, which may well help the OP in other situations where a regex may actually be the right approach.
    – Jon Skeet
    May 6, 2013 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.