0

I have following regex which I found from this website:

Bt somewhere the syntax is incorrect and it throws error:

var myDate = /^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][0-9]|3[01])\/(19|20)[0-9]{2};

Just to be clear:

Date can be anything between 01/01/1900 and 31/12/2099 but format should be strictly:

DD/MM/YYYY

I know there are several solutions on web, all similat but somehow it is throwing javascript error.

Probably syntax mistake because just above that i have put email validation which works fine:

var email = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
13
  • 3
    The first one misses a / at the end of the regex. Commented Jan 23, 2013 at 12:43
  • Also, you do not want to override the Date object. Commented Jan 23, 2013 at 12:44
  • 3
    Are you aware that this regex will match many invalid dates? Commented Jan 23, 2013 at 12:46
  • 1
    Who is voting those kind of questions up? Seriously, I don´t get it. Commented Jan 23, 2013 at 12:47
  • 1
    @Amberlamps - maybe those people who have made a slight syntax error in the past and not been able to see it (ie, every dev who has ever lived!). Not all questions have to be majorly cerebral. Commented Jan 23, 2013 at 12:50

1 Answer 1

5

The message from the console says

SyntaxError: unterminated regular expression literal

you're missing a / at the end of the line, so it should be

var myDate = /^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][0-9]|3[01])\/(19|20)[0-9]{2}/;

As pointed out in the comments, you may also have intended to put a $ at the end before the /. This indicates to regex that you should match the end of the string (see your email example later in the OP).

As an aside; validating the general format of a date using regex is valid and worthwhile. Trying to validate it's an actual real, valid (ie, not 30 feb 2012) date using regex is barmy. The regex to be able to do it properly would be pages upon pages long!

Sign up to request clarification or add additional context in comments.

3 Comments

And may be it needs $ before last /
@pstr - maybe, but seeing as the OP didnt include it, im not going to assume it should be there.
+1 for your aside. /^\d?\d\/\d?\d\/\d{4}$/ is enough to check the general format, or throw in some grouping parentheses to extract the pieces for a "real" date validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.