views:

99

answers:

3
/^\d{1,2}[:][0-5][0-9]$/

is what I have. this limits minutes to 00-59. It does not, however, limit hours to between 0 and 12. For similarity and uniformity I would like to do this with RegEx alone if possible.

Further-more I would like the first digit to be optional. i.e. 09:30 accepted as well as 9:30. I played around with ranges, but something out of range is always acceptable.

+6  A: 

The 0 - 9 and 10 - 12 cases need to be treated separately. (The two rules can be combined with |.)

/^(?:0?\d|1[012]):[0-5]\d$/

Here

  • (?:…) is a non-capturing group
  • x|y means match either pattern
  • 0?\d matches 0 - 9 or 00 - 09
  • 1[012] matches 10 - 12.
KennyTM
+1  A: 
/^(10|11|12|[1-9]):[0-5][0-9]$/

I don't think that you want 0:50 as a valid time either.

Jon Snyder
+1  A: 

Assuming you are working in 12 hour time, 0 is not a valid hour and should also be excluded (as pointed out by Jon). Here is a basic solution:

/^(0?[1-9]|1[012]):[0-5][0-9]$/

A 24-hour time regex matcher that works similarly:

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