我正在尝试使用JavaScript函数来验证字段中的月份和年份。该字段上日期的格式为mm / yyyy,验证它的功能如下:
function validateVencimento(){
var valid = true;
var currentTime = new Date();
var actualMonth = currentTime.getMonth() + 1;
var actualYear = currentTime.getFullYear();
vencimento = vencimento.replace('///g', '');
var month = parseInt(vencimento.substring(0, 2),10);
var year = parseInt(vencimento.substring(2, 6),10);
if((month < 1) || (month > 12)) valid = false;
if((year < actualYear)) valid = false;
if((year < actualYear) && (month < actualMonth)) valid = false;
if(valid == false){
vencimento.addClass("error");
vencimentoInfo.text("A validade do cartao esta invalida!");
vencimentoInfo.addClass("error");
return false;
}
else{
vencimento.removeClass("error");
vencimentoInfo.text("");
vencimentoInfo.removeClass("error");
return true;
}
}
我在字段上输入日期后,我在模糊时调用上面的函数,但Chrome控制台会返回错误Uncaught TypeError:Object#没有方法'replace'。
答案 0 :(得分:3)
看起来你正在使用vencimento
作为字符串和jQuery对象。你不能这样做。也许像这样制作一个新变量vencimentoText
:
var vencimentoText = vencimento.val();
然后使用vencimentoText
,无论您当前将其用作字符串(例如,使用replace
,substring
等,而不是addClass
等。)