4

I found a lot of links to validate string if it is a date.

Like here and here.

But anyway I cannot figure out how to validate if we have this thing:

6/6/2012 where first 6 is month and the second 6 is days

and also if user input it like that:

06/06/2012

Any clue how it could be done in a proper way?

Thanks!!

2 Answers 2

20

Here, this should work with any date format with 4 digit year and any delimiter. I extracted it from my plugin Ideal Forms which validates dates and much more.

var isValidDate = function (value, userFormat) {
  var

  userFormat = userFormat || 'mm/dd/yyyy', // default format

  delimiter = /[^mdy]/.exec(userFormat)[0],
  theFormat = userFormat.split(delimiter),
  theDate = value.split(delimiter),

  isDate = function (date, format) {
    var m, d, y
    for (var i = 0, len = format.length; i < len; i++) {
      if (/m/.test(format[i])) m = date[i]
      if (/d/.test(format[i])) d = date[i]
      if (/y/.test(format[i])) y = date[i]
    }
    return (
      m > 0 && m < 13 &&
      y && y.length === 4 &&
      d > 0 && d <= (new Date(y, m, 0)).getDate()
    )
  }

  return isDate(theDate, theFormat)

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

Comments

5

Use a regular expression.

var dateRegEx = /^(0[1-9]|1[012]|[1-9])[- /.](0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](19|20)\d\d$/

console.log("06/06/2012".match(dateRegEx) !== null) // true
console.log("6/6/2012".match(dateRegEx) !== null) // true
console.log("6/30/2012".match(dateRegEx) !== null) // true
console.log("30/06/2012".match(dateRegEx) !== null) // false

Learn about RegEx.

Edit - A Disclaimer

As @elclanrs pointed out, this only validates the string's format, and not the actual date, which means that dates like February 31st would pass. However, since the OP only asks "to validate date string format," I'll keep this answer here because for some, it might be all you need.

As a note, the jQuery Validation plugin that the OP was using, also only validates format.

Finally, for those wondering, if you needed to validate the date, and not just the format, this regular expression would have ~2% rate of failure over the domain of (1-12)/(1-31)/(1900-2099) date strings. Please don't use this in Mission Critical code for JPL.

4 Comments

This won't do it for every case ie. console.log("11/31/2012".match(dateRegEx)) // true
@elclanrs Um...isn't that a valid (M)M/(D)D/YYYY date string? Are you saying it should return false?
Well, November doesn't have 31 days...so yeah I guess it should return false.
@elclanrs - Aha! good catch...sometimes it's easy to get ahead of oneself.

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.