JavaScript: Regular Expression for Military Time

March 15, 2007 at 10:06 pm 16 comments

This post is more for my future reference than you.  Sorry to be so selfish!  :)

I had a need to use a regular expression via JavaScript to confirm if data entered into a text field was in military time format (e.g. 03:30, 23:59, etc).   With regular expressions, I’m still very much a scavenger.  I do a quick search and “borrow” something similiar to my needs and tweak it as necessary. 

Well most of the examples I found for military time regular expressions were a little suboptimal.  They would do something like this:

/\d{1,2}:\d{2}/

Where they are saying before the colon you can have 1-2 digits and then after the colon, you’d have 2 digits.  But that would permit stuff like 98:86.  So they would have subsequent JavaScript code to parse out the data and make sure the first number doesn’t exceed 23 and then make sure the second number doesn’t exceed 59.  Lame.  I wanted to do it all in one quick regular expression.  This is what I ended up with:

/(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)[:](0|1|2|3|4|5)\d{1}/

I would not be surprised if Clint can optimize this further (I have solicited his help on regular expressions before)– but for now, it’s sufficient for my needs.  It makes sure the hour ranges between 00 and 23, it ensures a colon is entered, it makes sure the minutes don’t go over 59.

A quick sample of the verification in use:

<HTML>
<BODY>
<SCRIPT LANGUAGE=”JavaScript”>
function CheckMe(myvalue)
{
   var re = /(00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23)[:](0|1|2|3|4|5)\d{1}/;
   if (!re.test(myvalue))
    {
       alert(‘false’);
        }
      else
        {
           alert(‘true’);
       }
    return;
}
</SCRIPT>
<FORM Name=”Form1″>
<INPUT TYPE=”Text” Name=”TestMe” SIZE=6>
<INPUT TYPE=”Button” onClick=”CheckMe(document.Form1.TestMe.value);” value=”Click Me”>
</FORM>
</BODY>
</HTML>

About these ads

Entry filed under: JavaScript, Web Development. Tags: .

The Dirty Potty Sicky Sawyer and the Kiddie Meals

16 Comments Add your own

  • 1. spugbrap  |  March 16, 2007 at 8:56 am

    Cool! I’ll probably use this regex next time I deal with data validation javascript code. Since I work on Navy webapps, military time is almost always used. I’m pretty sure that the validation that we currently use either does a series of if statements for each character in the time string, or uses an inadequate regex (i.e. one that would allow some invalid times, like your 98:86 example), or some combination of the two approaches.

    Reply
  • 2. Clint  |  March 16, 2007 at 9:57 am

    if ($s =~ /^[0-2]?[0-9]:[0-5][0-9]$/) { $valid=1; } else { $valid=0; }

    I’m being lazy though and not thinking about it. I’m probably missing something here.

    \d is nice, but I think [0-9] is more readable. I often choose a simpler more readable solution that programming snobs would scoff at — but I think [0-9] is more readable as a digit than \d.

    Note the question mark after the first [0-2]? — that means that char is optional. same thing as {1,2}.

    of course, you wanted javascript, not perl :)

    Reply
  • 3. Brian  |  March 16, 2007 at 1:15 pm

    Surprisingly annoying. Clint’s version allows the invalid hours 24 through 29. This seems to work:

    var re = /^([0-9]|[0-1][0-9]|2[0-3])[:][0-5][0-9]$/;

    It checks for a single hour digit, or 0 or 1 followed by any digit, or 2 followed by 0 through 3. The ^ and $ force the pattern to match on the entire string; in the original code something like “123:45″ returns true because the substring “23:45″ matches.

    Reply
  • 4. Clint  |  March 16, 2007 at 4:42 pm

    Hmm, good point Brian.

    Here’s my fix:

    if ($s =~ /^([0-2])?([0-9]):[0-5][0-9]$/) { $valid=1; } else { $valid=0; }
    if (($1==2) && ($2 >3)) { $valid=0 }

    I think it’s more readable, but that’s really a matter of opinion.

    Reply
  • 5. Clint  |  March 16, 2007 at 4:42 pm

    (it probably executes slower, though, haha)

    Reply
  • 6. Michael Ridley  |  March 19, 2007 at 2:12 am

    So why can’t you just do [0-2][0-3]:[0-5][0-9] ?

    -m

    Reply
  • 7. tgaw  |  March 19, 2007 at 9:11 am

    @Michael Ridley– haven’t seen you in some time!!! How do you get 16:30?

    Reply
  • 8. Michael Ridley  |  March 19, 2007 at 4:00 pm

    @tgaw – yeah it’s been ages, hope all is well with you. Not sure I understand your inquiry – 16:30 will match the regex in my comment. Drop me an email or give me a call if you are having troubles implementing :-)

    -m

    Reply
  • 9. tgaw  |  March 19, 2007 at 4:21 pm

    I don’t 16:30 will work because your second digit can only be between 0 and 3.

    Reply
  • 10. Justin  |  September 30, 2007 at 10:53 pm

    The regular expression I use to validate military time is as follows. It’s slightly more compact than Brian’s. Clint your current version would allow for 25-29 which may be undesirable for your use.

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

    Reply
  • 11. Frank  |  March 12, 2008 at 11:32 am

    @Justin – Thanks for this. Saved me some time.

    Alternatively what I’m using is:

    ^([0-1][0-9]|2[0-3])[:][0-5][0-9]$ (just removed the question mark) because I want to retain the leading zeros if the time is 7am for example. I would want it to fail if 7:00 is entered rather than 07:00

    Reply
  • 12. anand  |  May 22, 2009 at 1:08 pm

    function validateTime(inputObject,flag,message)
    {
    var re = /^((0[1-9])|(1[0-2])):[0-5][0-9] [AP]M/;
    if (!re.exec(inputObject.value))
    {
    if(flag)
    alert(message);
    //inputObject.value = “09:00 AM”;
    }
    }

    this validates time in xx:xx AM/PM format
    This can be changed to achieve wat u want very easily

    Reply
  • 13. anand  |  May 22, 2009 at 1:55 pm

    var re = /^(([01][0-9])|(2[0-3])):[0-5][0-9]$/;
    if (!re.exec(inputObject.value))
    {

    alert(message);

    }

    Reply
  • 14. juanma  |  June 5, 2009 at 12:36 pm

    Excelent anand! Thx!

    Reply
  • 15. AlGo  |  February 3, 2010 at 3:20 am

    Thanks anand !!!! Best checking!

    Reply
  • 16. totaldrugs  |  March 29, 2010 at 4:36 pm

    Best stake to unearth economical and good see to to find satisfactory evaluate pro pills in USA – online shop http://zyprexa-bestbuy.freehostia.com – HERE

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Flickr Photos

Dyson's Birthday - Playing with Dog Water

Dyson's First Birthday - Happy with new Airplane Toy

Dyson's First Birthday - Smiling with Airplane Gift

Dyson's First Birthday - Squinting at Camera with Chestnut Leaf in Background

Dyson's First Birthday - Sitting by the Chestnut

More Photos

3D Printed Products

Tweets

  • This vacation is also a vacation from the breast pump...and bottles! We didn't pack a single one! #fb 22 hours ago
  • Perk of all the Bay Bridge Traffic yesterday- Seeing the giant nest built over the highway on a traffic sign...with two ospeys in it!!! #fb 22 hours ago
  • Test server updated, July hours are in, and my Out of Office responder is set. I think...I think I may actually be on vacation! :) #fb 2 days ago
  • I don't think I ever expected to see the word 'merkin' show up in my Facebook feed. :) jezebel.com/women-want-bus… 2 days ago
  • One of this season's Project Runway contestants dresses up as Nyan Cat costume at Cosplay conventions! mylifetime.com/shows/project-… 3 days ago

Follow

Get every new post delivered to your Inbox.

Join 60 other followers

%d bloggers like this: