Beniamin Szabo
Beniamin Szabo

Reputation: 1929

RegExp date validation in javascript

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?

Upvotes: 1

Views: 844

Answers (2)

anubhava
anubhava

Reputation: 786091

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");

Upvotes: 2

Markus
Markus

Reputation: 202

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).

Upvotes: 1

Related Questions