我想使用mm/dd/yyyy
格式验证输入的日期格式。
我在一个网站上找到了下面的代码,然后使用了它,但它不起作用:
function isDate(ExpiryDate) {
var objDate, // date object initialized from the ExpiryDate string
mSeconds, // ExpiryDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (ExpiryDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert ExpiryDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
function checkDate(){
// define date string to test
var ExpiryDate = document.getElementById(' ExpiryDate').value;
// check date and print message
if (isDate(ExpiryDate)) {
alert('OK');
}
else {
alert('Invalid date format!');
}
}
有什么建议可能是错误的吗?
发布于 2011-05-30 23:51:42
我认为Niklas对你的问题有正确的答案。除此之外,我认为下面的日期验证函数更容易阅读:
// 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];
};
发布于 2013-07-02 17:46:36
使用以下正则表达式进行验证:
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testDate))) {
return false;
}
这对我来说适用于MM/dd/yyyy。
发布于 2011-05-30 23:24:04
它似乎可以很好地处理mm/dd/yyyy格式的日期,例如:
http://jsfiddle.net/niklasvh/xfrLm/
我对你的代码唯一的问题是:
var ExpiryDate = document.getElementById(' ExpiryDate').value;
在括号内的元素ID之前有一个空格。将其更改为:
var ExpiryDate = document.getElementById('ExpiryDate').value;
如果没有关于不起作用的数据类型的任何进一步细节,就没有太多其他信息可以输入。
https://stackoverflow.com/questions/6177975
复制相似问题