Reputation: 557
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!
Upvotes: 2
Views: 2027
Reputation: 8134
I guess @joe-hanink's answer in JSBin seems to be correct to me! Anyway, I'm doing iOS Development. I needed the Credit Card validation too. While in search of the correct regEx for that I found the following link:
In there I found the following connected RegEx, and used it successfully in iOS, Objective-C method:
^(?:4[0-9]{12}(?:[0-9]{3})? # Visa
| 5[1-5][0-9]{14} # MasterCard
| 3[47][0-9]{13} # American Express
| 3(?:0[0-5]|[68][0-9])[0-9]{11} # Diners Club
| 6(?:011|5[0-9]{2})[0-9]{12} # Discover
| (?:2131|1800|35\d{3})\d{11} # JCB
)$
And it works like a charm!
Hope this might be helpful to you all!
Good day!
Upvotes: 1
Reputation: 4857
This code works. see - http://jsbin.com/aqowa3
To view the code + html, see - http://jsbin.com/aqowa3/edit
Make sure your html is consistent with your js and make sure you are calling your function after the dom is ready.
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";
} else{
document.forms[0].ccResult.value = "Invalid credit card number";
}
}
Upvotes: 1