Welcome to WebmasterWorld Guest from 54.196.244.186

Forum Moderators: open

Message Too Old, No Replies

Regular expression help needed

Date matching

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

Junior Member

10+ Year Member

joined:Jan 26, 2006
posts: 41
votes: 0


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 Sept 12, 2008 (gmt 0)

Senior Member

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

joined:Mar 15, 2002
posts:6807
votes: 0


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 Sept 12, 2008 (gmt 0)

Junior Member

10+ Year Member

joined:Jan 26, 2006
posts: 41
votes: 0


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 Sept 17, 2008 (gmt 0)

Junior Member

10+ Year Member

joined:Jan 26, 2006
posts: 41
votes: 0


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