I'm not receiving the correct output from the credit card detection jQuery I've put together. The keyup event calls a function, creditCardTypeFromNumber(num), and the credit card type is supposed to be detected. Unfortunately, the only thing that is returned is 'UNKNOWN' no matter what value is typed in. I've used 6011 (discover), 5155 (MasterCard), and 4147 (Visa), none of which works.
I used the RegEx of each Credit Card type from the post here:
How do you detect Credit card type based on number?
And I put these two functions together based on what was done here:
I've put together a JSFiddle to show it not working. If someone could help me, I'd really appreciate it. Thanks
creditCardTypeAction();
/**
* Detect Credit Card Type Function
*/
function creditCardTypeAction(){
$('.creditcardnumber').on('keyup', function(){
if($(this).val().length >= 4){
cardType = creditCardTypeFromNumber($(this).val());
}
});
}
function creditCardTypeFromNumber(num) {
// first, sanitize the number by removing all non-digit characters.
num = num.replace(/[^\d]/g,'');
// MasterCard
if (num.match(/^5[1-5][0-9]{5,}$/)) {
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.mastercard').addClass('active');
alert('MasterCard');
return 'MasterCard';
// Visa
} else if ( num.match(/^4[0-9]{6,}$/) ) {
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.visa').addClass('active');
alert('Visa');
return 'Visa';
/* AMEX */
} else if (num.match(/^3[47][0-9]{5,}$/)) {
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.amex').addClass('active');
alert('AMEX');
return 'AMEX';
// Discover
} else if (num.match(/^6(?:011|5[0-9]{2})[0-9]{3,}$/)) {
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.discover').addClass('active');
alert('Discover');
return 'Discover';
// Diners Club
} else if (num.match(/^3(?:0[0-5]|[68][0-9])[0-9]{4,}$/)){
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.diners').addClass('active');
alert('Diners Club');
return 'Diners Club';
// JCB
} else if (num.match(/^(?:2131|1800|35[0-9]{3})[0-9]{3,}$/)){
$('.cardsacceptedicon').removeClass('active');
$('.cardsacceptedicon.jcb').addClass('active');
alert('JCB');
return 'JCB';
}
alert('UNKNOWN');
return 'UNKNOWN';
}