Welcome to WebmasterWorld Guest from 54.163.168.15

Forum Moderators: open

Regular expression help needed

Date matching

   
4:57 pm on Sep 12, 2008 (gmt 0)

5+ Year Member



Hi,

I'm pretty new to regular expressions and need a little help figuring out why my expression seems to be incorrectly evaluated.

My scenario: I need to test a value and see if it's in the format ##/##/##. It's a date (month/day/year), but I can't get the expression to return false. In other words every value is returning true, even "On shelf", which obviously shouldn't.

Here's my javascript:
if (duedate.match(/((\d{2})\/)*/)) {
checkedout++;
}

The idea is to look for the pattern ##/ repeating any number of times.

What am I missing?

Thanks for you help!

Glenn

5:12 pm on Sep 12, 2008 (gmt 0)

WebmasterWorld Senior Member drdoc is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Well, your pattern would match something like:
00/
00/00/
00/00/00/
00/00/00/00/
etc.
(In fact, it would even match "foo 99/ bar".)

But not:
00
00/00
00/00/00

Do you see the problem? Your pattern requires a trailing slash.

However, I would improve the pattern to explicitly look for a string in the format #/##/## or ##/##/## thus:

duedate.match(/^\d{1,2}\/\d{2}\/\d{2}$/)

If you want to get it even better, you should probably do something like this:

duedate.match(/^(?:0?[1-9]¦1[0-2])\/(?:0?[1-9]¦[12][0-9]¦3[01])\/\d{2}$/)

Remember to replace the broken bar ¦ with an actual vertical bar.

Of course, invalid dates like 2/30/08 would still be allowed through. But that will be handled by your server side validation.

6:20 pm on Sep 12, 2008 (gmt 0)

5+ Year Member



Thanks for the reply and help.

Unfortunately, I'm getting an error in Firebug about an "unterminated regular expression literal".

Here's the updated code:
if (duedate.match(/^\d{1,2}\/\d{1,2}\/\d{2}$/)) {
checkedout++;
}

Maybe my eyes are going bad. What could be unterminated?

Thanks again,
Glenn

4:42 pm on Sep 17, 2008 (gmt 0)

5+ Year Member



Hi,

Fixed it. Here's what worked for me:

var duedatematch = /^\d{1,2}\/\d{1,2}\/\d{2}/ <== There is no semi-colon

if (duedatematch.test(duedate)){
checkedout++;
}

For some reason, when the regexp was inside parens in the earlier suggestion, that final "/" in the pattern was apparently somehow causing the one of the enclosing parens to be escaped(!), thus the "unterminated" javascript error was generated. No idea how that could be possible since "\" is the escape character!

Hmm.

Anyway, I hope this helps someone else.

Glenn

 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month