Skip to content

Instantly share code, notes, and snippets.

@madrobby madrobby/gist:127183
Created Jun 10, 2009

Embed
What would you like to do?
var CreditCard = {
CARDS: {
Visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
MasterCard: /^5[1-5][0-9]{14}$/,
DinersClub: /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/,
Amex: /^3[47][0-9]{13}$/,
Discover: /^6(?:011|5[0-9]{2})[0-9]{12}$/
},
TEST_NUMBERS: $w('378282246310005 371449635398431 378734493671000 '+
'30569309025904 38520000023237 6011111111111117 '+
'6011000990139424 5555555555554444 5105105105105100 '+
'4111111111111111 4012888888881881 4222222222222'
),
validate: function(number){
return CreditCard.verifyLuhn10(number)
&& !!CreditCard.type(number)
&& !CreditCard.isTestNumber(number);
},
verifyLuhn10: function(number){
return ($A(CreditCard.strip(number)).reverse().inject(0,function(a,n,index){
return a + $A((parseInt(n) * [1,2][index%2]).toString())
.inject(0, function(b,o){ return b + parseInt(o) }) }) % 10 == 0);
},
isTestNumber: function(number){
return CreditCard.TEST_NUMBERS.include(CreditCard.strip(number));
},
strip: function(number) {
return number.gsub(/\s/,'');
},
type: function(number) {
for(card in CreditCard.CARDS)
if(CreditCard['is'+card](number)) return card;
}
};
for(card in CreditCard.CARDS)
CreditCard['is'+card] = function(card, number){
return CreditCard.CARDS[card].test(CreditCard.strip(number));
}.curry(card);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.