1

I just learned regular expressions and I created a dd-mm-yyyy date validator with regular expressions:

^(0[1-9]|[12][0-9]|3[01])([-/.])(0[1-9]|1[0-2])\2(19|20)\d\d$

Regular expression visualization

Debuggex Demo

It seems to work fine. But i was wondering if there are any improvements that could be made to make sure there will be no errors. Any suggestions?

2
  • This kind of validation is impossible (or, at least, not practical) with regular expressions. Dates are not strings. Commented Oct 7, 2013 at 15:26
  • what about 1/1/2000 seems like a valid data to me, not everyone add leading 0 Commented Oct 7, 2013 at 23:42

2 Answers 2

2

Why reinvent the wheel. Take help of built-in date parsing method Date.parse(String) like this:

var timestamp = Date.parse(str); // str is your input string for data
var date = null
if (isNaN(timestamp) == false)
    date = new Date(timestamp);
else
    alert("Invalid date");
Sign up to request clarification or add additional context in comments.

1 Comment

Date.parse wraps invalid dates, so 2013-02-29 will be validated.
1

Maybe you want to include moment.js into your project? Then you can just write:

moment("not a real date").isValid(); // false

You can also use your own format string if you want to. ;-) This would also give you the advantage that it veryfies if the date actually exists (think of 29-02-2013, which is not existant).

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.