Forum Moderators: open
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
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.
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