Amazon.com Widgets

Regular Expression to Check for Minutes:Seconds (XX:XX) Format

I wish I knew more about Regular Expressions. I'm slowly learning and discovering how frickin' all mighty and powerful they are. Here's an example.

I have a field in my app where I need to make sure that users enter a time-like format, but not an actual time. I want them to enter how long in minutes and seconds it took them to do something. And I don't want to use two separate form fields.

Therefore, they might enter 36:15, which is 36 minutes, 15 seconds... obviously not a real time-of-day.

If you need to verify an actual time-of-day, just look at my previous post about using the ColdFusion IsDate() function to validate time. But if you need to do what I'm doing, check out this RegEx I created. I'm still new at RegEx, so there might be an even better way to do this.

<cfset myVar = "36:15">

<cfif ReFind("^[0-9]{1,3}:[0-9]{2}$", myVar, "1")>
   This is valid.
<cfelse>
   This is NOT valid.
</cfif>

This does exactly what I need it to do. And it will even accommodate really slow users who enter something like 114:38. But any other format will generate a message that they entered their info in the wrong format.

What's going on?

1) The carat "^" tells the RegEx to start at the beginning of the string. There it looks for any single number [0-9].

2) Next, we tell it to do this at least 1 time and not more than 3 times {1,3}.

3) Then we have a literal character ":" which is an actual character to look for.

4) Then we check for exactly 2 more numbers.

5) The "$" locks the end of the string after those two numbers have been found.

Comments
Graham's Gravatar Cool. I just wrote a regex to find a valid time in a day with a min portion of 15,30 or 45.:
^([1-9]|10|11|12){1}(:(00|15|30|45))?(am|pm)$

"8am","9:30pm","11:45pm"
# Posted By Graham | 9/2/08 9:28 AM

Raymond Camden's BlogCFC version 5.8.001