1

I need a regex to pattern match the following -

mm/dd/yyyy

The following date entries should pass validation:

  • 05/03/2012
  • 5/03/2012
  • 05/3/2012
  • 5/3/2012

Also, after validating above regex, what is the best way convert above date string to Date object?

Parag Meshram
  • 8,281
  • 10
  • 52
  • 88

4 Answers4

1

You should do the check and the parsing in one go, using split, parseInt and the Date constructor :

function toDate(s) {
  var t = s.split('/');
  try {
     if (t.length!=3) return null;
     var d = parseInt(t[1],10);
     var m = parseInt(t[0],10);
     var y = parseInt(t[2],10);
     if (d>0 && d<32 && m>0 && m<13) return new Date(y, m-1, d);
  } catch (e){}
}

var date = toDate(somestring);
if (date) // ok
else // not ok

DEMONSTRATION :

01/22/2012 ==> Sun Jan 22 2012 00:00:00 GMT+0100 (CET)
07/5/1972 ==> Wed Jul 05 1972 00:00:00 GMT+0100 (CEST)
999/99/1972 ==> invalid

As other answers of this page, this wouldn't choke for 31 in February. That's why for all serious purposes you should instead use a library like Datejs.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Interesting solution but it will happily accept 99/99/99 as a valid date. The JavaScript Date function will produce a valid date form any any numeric values. You should validate them before calling date. – HBP Oct 17 '12 at 11:48
  • @HBP +1 You're right... I didn't think about that. I'll fix it. – Denys Séguret Oct 17 '12 at 11:49
  • @HBP But as other answers here, it's still happy with 02/31/2012. So I recommend to use a library like Datejs (or another but I use Datejs without problem). – Denys Séguret Oct 17 '12 at 11:55
0

This one should do it:

((?:[0]?[1-9]|[1][012])[-:\\/.](?:(?:[0-2]?\\d{1})|(?:[3][01]{1}))[-:\\/.](?:(?:[1]{1}\\d{1}\\d{1}\\d{1})|(?:[2]{1}\\d{3})))(?![\\d])

(It is taken from txt2re.com)

You should also take a look at this link.

Community
  • 1
  • 1
oopbase
  • 11,157
  • 12
  • 40
  • 59
0
"/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/"

link: Javascript date regex DD/MM/YYYY

Community
  • 1
  • 1
Yogesh
  • 1,206
  • 4
  • 22
  • 50
0
var dateStr = '01/01/1901',
    dateObj = null,
    dateReg = /^(?:0[1-9]|1[012]|[1-9])\/(?:[012][1-9]|3[01]|[1-9])\/(?:19|20)\d\d$/;
    //             01 to 12 or 1 to 9   /    01 to 31  or  1 to 9   /  1900 to 2099

if( dateStr.match( dateReg ) ){
    dateObj = new Date( dateStr ); // this will be in the local timezone
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138