1

I am facing a problem of date validation. I used following reg expression for enter date in dd-mmm-yyyy format only

dateValidatorRegex = /^(\d{1,2})(-)(?:(\(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec))(-)(\d{4})$/i;

But in this case when I entered date in month of jan It doesn't passes the validation. Please suggest on it.

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
sushama
  • 643
  • 1
  • 7
  • 15
  • 2
    Why the backslash before the opening parenthesis right before `jan`? – Frédéric Hamidi Jun 30 '14 at 07:41
  • possible duplicate of [Validate two dates of this "dd-MMM-yyyy" format in javascript](http://stackoverflow.com/questions/3509683/validate-two-dates-of-this-dd-mmm-yyyy-format-in-javascript) – Sid M Jun 30 '14 at 07:45

2 Answers2

2

Here is an alternative to lengthy regexs which do not handle leap years

Live Demo

function isValidDate(str) {
  var d = new Date(Date.parse(str.replace(/-/g," "))), parts = str.split("-");
  var monthNum = ["jan","feb","mar","apr","may","jun","jul",
                  "aug","sep","oct","nov","dec"].indexOf(parts[1].toLowerCase());
  return parts[0]==d.getDate() && 
         monthNum == d.getMonth() && 
         parts[2]==d.getFullYear();
}

Note that the .indexOf for arrays is not compatible with older IEs so you can do

  var monthNum = {"jan":0,"feb":1,"mar":2,"apr":3,"may":4,
                  "jun":5,"jul":6,"aug":7,"sep":8,"oct":9,
                  "nov":10,"dec":11].[parts[1].toLowerCase()];

instead

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Liked your Live Demo button. Keen to know where did you get hold of that. Would love to use next time :) – Shubh Jun 30 '14 at 09:03
  • I got it from here a long time ago. Some purist edit my posts to remove it. Not sure why. – mplungjan Jun 30 '14 at 09:07
1

The regular expression is wrong at backslash. It will be,

var dateValidatorRegex = /^(\d{1,2})(-)(?:((jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)))(-)(\d{4})$/i;

By that backslash jan month is not validate.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
sushama
  • 643
  • 1
  • 7
  • 15