1

Possible Duplicate:
Regular expression to validate valid time

i wrote this code for validating time in asp.net *

what are the errors if i use "[0-9]?[0-9]+:[0-9]+[0-9]+:[0-9]+[0-9]+" for hh:mm:ss format.Will it work for all cases?

Community
  • 1
  • 1
user1799214
  • 511
  • 2
  • 11
  • 25
  • It will not work in all cases, you are missing culture information. If you know that the date/time is always in the same culture it will work. – PapaAtHome Nov 14 '12 at 08:09

2 Answers2

3

You may use TimeSpan.TryParse rather than regex to parse a string and see if you get true or false

TimeSpan tempTimeSpan;
if (TimeSpan.TryParse("12:22:33", out tempTimeSpan))
{
    //valid time
}
else
{
    //Invalid time
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    the user enters the value in textbox i am trying to validate it using regular expression – user1799214 Nov 14 '12 at 07:33
  • Why regular expression ? If the format is different, then you may use [`TimeSpan.TryParseExact`](http://msdn.microsoft.com/en-us/library/dd784009.aspx) with the format. – Habib Nov 14 '12 at 07:35
  • It will not work in all cases, you are missing culture information. If you know that the date/time is always in the same culture it will work – PapaAtHome Nov 14 '12 at 08:11
0

Below code snippet of regex could be of help for validating dates with time. This takes care of leap year also.

^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$ 
user851316
  • 29
  • 1
  • 3