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.

2

2 Answers 2

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

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

2 Comments

Liked your Live Demo button. Keen to know where did you get hold of that. Would love to use next time :) <kbd></kbd>
I got it from here a long time ago. Some purist edit my posts to remove it. Not sure why.
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.

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.