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?

1

4 Answers 4

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.

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

3 Comments

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 +1 You're right... I didn't think about that. I'll fix it.
@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).
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.

Comments

0
"/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/"

link: Javascript date regex DD/MM/YYYY

Comments

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
}

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.