Last Updated: February 25, 2016
·
1.642K
· elclanrs

Validate a date effectively with any delimiter and 4 digit year

/* Validate a date from string effectively with
* any delimiter and 4 digit year.
* @param value The value of the input.
* @param userFormat The user format with 4 digit year.
* @return bool
*/
function isValidDate (value, userFormat) {

  userFormat = userFormat || 'mm/dd/yyyy'

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

  function isDate (date, format) {
    var m, d, y, i = 0, len = format.length, f
    for (i; i < len; i++) {
      f = format[i]
      if (/m/.test(f)) m = date[i]
      if (/d/.test(f)) d = date[i]
      if (/y/.test(f)) 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)

}

// Usage:
// This will return FALSE,
// November doesn't have 31 days
console.log( isValidDate('dd/mm/yyyy', '31/11/2012') )

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside