用JavaScript信用卡验证无法弄清楚我的语法错误

时间:2014-10-17 20:31:11

标签: javascript validation debugging

我正在学习JavaScript,并且正在尝试在表单中进行信用卡验证。我在下面的代码的第10行得到语法错误,无法弄清楚我做错了什么。我还注意到当我在Text Wrangler中添加最后一个花括号时,它说我有一个无与伦比的花括号,但是如果我经过并计算它们它们似乎匹配,所以我不知道我哪里出错了?

<script type="text/javascript">
function validateCard() {
if (document.forms[0].cardName.value == "American Express") {
    var cardProtocol = new RegExp("^3[47][0-9]{13}$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    } 
else if (document.forms[0].cardName.value == "Diners Club" {
    var cardProtocol = new RegExp ("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
else if (document.forms[0].cardName.value == "Discover" {
    var cardProtocol = new RegExp ("^6(?:011|5[0-9]{12}$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
else if (document.forms[0].cardName.value == "JCB" {
    var cardProtocol = new RegExp ("^(?:2131|1800|35\d{3})\d{11}$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
else if (document.forms[0].cardName.value == "Mastercard" {
    var cardProtocol = new RegExp ("^5[1-5][0-9]{14}$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
else if (document.forms[0].cardName.value == "Visa" {
    var cardProtocol = new RegExp ("^4[0-9]{12}(?:[0-9]{3})?$");
    if (cardProtocol.test(document.forms[0].cardNumber.value))
        document.forms[0].ccResult.value = "Valid credit card number";
    else
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
}
</script>

1 个答案:

答案 0 :(得分:3)

if的条件没有结束)else没有开放{等等。您可以使用JSHint之类的工具来检查语法。