Joe*_*Bob 1 javascript validation date
validateDate()调用时函数不执行的原因是什么?
目的validateDate()是获取类似的字符串01/01/2001并调用isValidDate()以确定日期是否有效.
如果它无效,则会出现警告消息.
function isValidDate(month, day, year){
/*
Purpose: return true if the date is valid, false otherwise
Arguments: day integer representing day of month
month integer representing month of year
year integer representing year
Variables: dteDate - date object
*/
var dteDate;
//set up a Date object based on the day, month and year arguments
//javascript months start at 0 (0-11 instead of 1-12)
dteDate = new Date(year, month, day);
/*
Javascript Dates are a little too forgiving and will change the date to a reasonable guess if it's invalid. We'll use this to our
advantage by creating the date object and then comparing it to the details we put it. If the Date object is different, then it must
have been an invalid date to start with...
*/
return ((day == dteDate.getDate()) && (month == dteDate.getMonth()) && (year == dteDate.getFullYear()));
}
function validateDate(datestring){
month = substr(datestring, 0, 2);
day = substr(datestring, 2, 2);
year = substr(datestring, 6, 4);
if(isValidDate(month, day, year) == false){
alert("Sorry, " + datestring + " is not a valid date.\nPlease correct this.");
return false;
} else {
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
substr不是一个功能本身; 你必须使用string.substr(start_index, length).
由于JavaScript substr方法只接受两个参数,而不是三个参数,这会导致执行停止在第一个子行,并且您永远不会从该函数获得输出.
我通过在测试HTML页面中运行代码时打开Firebug找到了这个.我强烈建议使用Firebug进行JavaScript调试.
在您的validateDate函数或类似的东西中尝试这个:
month = datestring.substr(0, 2);
day = datestring.substr(3, 2);
year = datestring.substr(6, 4);
Run Code Online (Sandbox Code Playgroud)