Javascript: 如何验证 MM-DD-YYYY 格式的日期?

我在这里看到了一个可能的答案,但那是针对 YYYY-MM-DD 的: JavaScript 日期验证

我对上面的代码进行了修改,使其适用于 MM-DD-YYYY,但仍无法正常工作:

String.prototype.isValidDate = function() 
{
     var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
     var matches = IsoDateRe.exec(this);
     if (!matches) return false;
     var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
     return ((composedDate.getMonth() == (matches[1] - 1)) &&
      (composedDate.getDate() == matches[2]) &&
      (composedDate.getFullYear() == matches[3]));
}

我怎样才能让上面的代码在 MM-DD-YYYY 以及 MM/DD/YYYY 上运行?

谢谢。

我使用这个 regex 来验证 MM-DD-YYYY:

function isValidDate(subject){
  if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
    return true;
  }else{
    return false;
  }
}

它只匹配有效的月份,您可以使用 / - 或 .作为分隔符。

评论(4)

这里有一个测试版本:

String.prototype.isValidDate = function()   {

    var match   =   this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    var test    =   new Date(match[3], match[1] - 1, match[2]);
    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true
评论(0)

将函数的前两行改成这样,就可以简化一些:

var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);

或者,只需将 RegExp 构造函数的参数改为

^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
评论(0)