2013-04-28 38 views
-1

我正在尝试使JavaScript函数验证字段中的月份和年份。在球场上的日期的格式是MM/YYYY并验证它下面的一个功能:Uncaught TypeError:Object#<Object> has no method'replace'

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

请问行号?一个jsFiddle测试用例也会有很大的帮助。 – 2013-04-28 22:11:49

+6

'vencimento'在哪里定义? – Matthew 2013-04-28 22:12:04

+0

哦,不需要,代码中只有一个'replace',哈哈哈。 你在哪里定义了'vencimento'变量?它在全球范围内吗? – 2013-04-28 22:12:37

回答

3

它看起来像你使用vencimento作为一个字符串和一个jQuery对象。你不能那样做。也许做一个新的变量vencimentoText这样的:

var vencimentoText = vencimento.val(); 

无论你目前正在使用它作为一个字符串,然后使用vencimentoText(例如,replacesubstring等,但不addClass等)

+0

@ T.J.Crowder:在没有任何其他信息的情况下,'text','addClass'和'removeClass'方法指示jQuery。 – icktoofay 2013-04-28 22:15:28

+0

@ ick:是的,对不起,我刚刚看到那些(但是在看到评论之前可惜没有删除!)。我认为你在那里相当稳固。 :-) – 2013-04-28 22:15:52

+0

@ T.J.Crowder,'.addClass','.removeClass'和'.text'听起来很漂亮jQuery-ish。 – 2013-04-28 22:16:09

相关问题