Jump to content

regular expression that matches the time without the am/pm


kee2ka4

Recommended Posts

When needing a validation such as this, it is very important to have explicit, definitive rules. You gave a few examples of what should pass, but it is not enough. The easy approach would be to validate that the string starts with one or two numbers, has a colon, and then has two more numbers. But, that means 25:01 or 10:99 would pass. Is that acceptable? I don't know your situation. Also, if 00:00 is valid is 24:00 valid as well?

 

Here is one possible solution:

function validTimeStr($timeStr)
{
    return (preg_match("/^((\d|[0-1]\d|2[1-3]):[0-5]\d)|24:00$/", $timeStr)>0);
}

 

Output of tests:

00:00: true
1:25: true
01:25: true
001:25: false
11:59: true
2:64: false
23:23: true
24:00: true
24:01: false

 

You should test against anything else you think might be problematic.

The regex rule you defined its fine but without the ":" right at the end.

 

The ":" at the end was just part of my unit test code couput. It has nothing to do with the function. The function will simply return true/false based upon whether the passed value matches the pattern.

I'd try a pattern like this:

'/^(0{0,1}[1-9]|1\d|2[0-3])[0-5]\d)$/'

 

That won't work for 24:00 as requirested by the OP. Although, I do see I had an error in my original code for the hour "20". And, that does give me an idea on shortening the original pattern to:

return (preg_match("/^(([0-1]?\d|2[0-3]):[0-5]\d)|24:00$/", $timeStr)>0);

 

- not tested

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.