通过jQuery验证日期字符串格式的最佳方法

问题描述:

如果是日期,我发现了很多验证字符串的链接。

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

喜欢 here 这里

但无论如何我无法弄清楚如果我们有这个东西验证:

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

6/6/2012 首先 6 是月,第二 6 是天

如果用户输入的话:

06/06/2012

如何以正确的方式完成任务?

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

谢谢!!

在这里,这应该适用于任何具有4位数年份和任何分隔符的日期格式。我从我的插件理想表格中提取它,验证日期等等。

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)

}