use*_*662 5 javascript validation datetime
我有一个HTML文本字段.我想通过JavaScript验证输入的值是"MM/DD/YY"或"MM/D/YY"或"MM/DD/YYYY"或"MM/D/YYYY"形式的有效日期.有没有这样做的功能?
我有点假设有类似isNaN的东西,但我没有看到任何东西.JavaScript无法验证日期是真的吗?
JavaScript无法验证日期是真的吗?
没有.
有没有这样做的功能?
没有.
您需要编写自己的验证函数来解析日期格式(想到正则表达式),然后确定它是否在您的特定条件中有效.
小智 7
您可以使用javascript自己的Date对象来检查日期.由于日期对象允许使用月和日值(例如3月32日将更正为4月1日),您可以检查您创建的日期是否与您放入的日期相匹配.如果您需要,可以缩短此项,但清晰度更长.
function checkDate(m,d,y)
{
try {
// create the date object with the values sent in (month is zero based)
var dt = new Date(y,m-1,d,0,0,0,0);
// get the month, day, and year from the object we just created
var mon = dt.getMonth() + 1;
var day = dt.getDate();
var yr = dt.getYear() + 1900;
// if they match then the date is valid
if ( mon == m && yr == y && day == d )
return true;
else
return false;
}
catch(e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)