Credit card validation with regexp using test()

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2011-02-06T06:59:35Z Indexed on 2011/02/06 7:25 UTC
Read the original article Hit count: 116

Filed under:
|

I'm trying to complete some homework and it appears the book might have gotten it wrong. I have a simple html page that allows user to pick a credit card in our case american express. The user then enters a number and evalutes that number based on a regular expression. My question ends up being when test() evaluates the number it returns a boolean or a string? I should then compare that string or boolean? True == true should fire off the code in a nested if statement. Heres what the book gives me as valid code:

if(document.forms[0].cardName.value == "American Express")
{
    var cardProtocol = new RegExp("^3[47][0-9]{13}$"); //REGEX ENTRY HERE
    if(cardProtocol.test(document.forms[0].cardNumber.value))     
        document.forms[0].ccResult.value = "Valid credit card number";
}

The above code doesn't work in firefox. I've tried modifying it with 2 alerts to make sure the number is good and the boolean is good...and still no luck:

if(document.forms[0].cardName.value == "American Express")
{
    var cardProtocol = new RegExp("^3[47][0-9]{13}$"); //REGEX ENTRY HERE <------
    alert(document.forms[0].cardNumber.value)
    alert(cardProtocol.test(document.forms[0].cardNumber.value))
    if((cardProtocol.test(document.forms[0].cardNumber.value)) == true ) // <--Problem
    {
        document.forms[0].ccResult.value = "Valid credit card number";
    }
    else
    {
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
}

Any ideas? the if loop is the culprit but I'm not figuring out why it is not working. Please throw up the code for the if loop! Thanks for the help!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about homework