Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

validation - Javascript: how to validate dates in format MM-DD-YYYY?

I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation

I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:

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

How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?

Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function isValidDate(date)
{
    var matches = /^(d{1,2})[-/](d{1,2})[-/](d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

It works. (Tested with Firebug, hence the console.log().)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...