Best way to validate date string format via jQuery

前端 未结 2 1704
星月不相逢
星月不相逢 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)
    
    }
    
    0 讨论(0)
  • 2020-11-30 15:47

    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.

    0 讨论(0)
提交回复
热议问题