码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript Validate a Valid Date formatted as "mm/dd/yyyy"

时间:2015-08-06 20:02:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate(dateString) {
// First check for the pattern
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
return false;
}
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);

// Check the ranges of month and year
if (year < 1000 || year > 3000 || month == 0 || month > 12) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;

// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};

JavaScript Validate a Valid Date formatted as "mm/dd/yyyy"

标签:

原文地址:http://www.cnblogs.com/TddCoding/p/4708820.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!