Search code examples
jqueryregexinputmaskingmaskedinput

Can anyone fix this 12/24 hour time regexp?


I have been scouring the internet for a way of doing 12/24 hour time format only ( _ _ : _ _ with no AM/PM) validation. The requirement is that it must actively prevent keypresses that would invalidate the time. It also must accept either 1 or 2 digits before the colon not over 23 and require 2 digits after it no over 59.

I have used both jquery inputmask and maskedinput to no avail. Whatever I try they just don't behave exactly right.

I finally found this article http://blog.pierrejeanparra.com/2011/10/time-input-mask-regexp-powered/ that contains some good logic and results in an almost perfect regexp that can be tied in with regexp mask to get the desired behavior. Unfortunately there is just one tiny bug left in this expression that I have been racking my brains over and just cannot figure out. The expression is as follows

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

The problem remaining with it is that it allows 1:6 because the [0-5] is optional. If I try to remove ? after [0-5] then the : doesn't work anymore. Help would be very appreciated. I know this is a common problem that doesn't seem to have any perfectly working solutions.

Here is a plnkr that demonstrates

http://plnkr.co/edit/OE6PGTuCvQa380S7b8Zg?p=preview


Solution

  • Here was the answer if anyone is interested.

    ^((([0-1][0-9]|2[0-3]|[0-9])|([0-1][0-9]|2[0-3]|[0-9])(:|h)|([0-1][0-9]|2[0-3]|[0-9])|([0-1][0-9]|2[0-3]|[0-9])(:|h)[0-5][0-9]?))$