Best way to validate date string format via jQuery

前端 未结 2 1721
星月不相逢
星月不相逢 2020-11-30 15:39

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:

2条回答
  •  不知归路
    2020-11-30 15:45

    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)
    
    }
    

提交回复
热议问题