1

I am looking for a regular expression that will accept date formats, both MM/DD/YYYY and M/D/YYYY

I found one here

However when I run that I get an unexpected illegal token. Here is how I am implementing the javascript function

return RegExp(/^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/).test(txtDate);

I've been told the http://regexlib.com website usually works well for .net regular expressions, but not javascript.

Any help would be great!

0

4 Answers 4

1

Escape the slashes inside the regex.

/^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/
             here __^                                         __^                        __^ ___^                   ___^___^
Sign up to request clarification or add additional context in comments.

4 Comments

I'm a newbie to this can I do that with the "\"
@JonHarding: Just insert a backslash ` before each slash /` as shown in my answer.
I just realized this regex only goes back to 1900, any ideas on a quick fix?
@JonHarding: I'm afraid there's no quick way to fix it. The regex will become very complicated.
0

for MM/DD/YY /^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/

for M/D/Y /^(\d{1,2})[./-](\d{1,2})[./-](\d{2}|\d{4})$/

Comments

0

Recipe 4.4 from Regex Cookbook does most of what you are looking for:

^(1[0-2]|0?[1-9])/(3[01]|[12][0-9]|0?[1-9])/(?:[0-9]{2})?[0-9]{2}$

Comments

0

Take a look at this:

http://jsfiddle.net/oscarj24/32JQr/

hope this helps

Comments

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.