Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to validate date string format via jQuery

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!!

like image 650
Friend Avatar asked Nov 28 '22 02:11

Friend


1 Answers

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)

}
like image 196
elclanrs Avatar answered Dec 05 '22 07:12

elclanrs