16 April 2008

Credit Card Validation with Luhn

I found an interesting article on using the Luhn algorithm to validate credit cards. I'd heard of the algorithm before but didn't know how it worked; it's actually much simpler than I imagined. The idea of the article (validating credit card numbers client-side with Javascript) is a good one, but I thought the actual javascript implementation was fairly poor, so I rewrote it. So if anyone wants to validate credit card numbers for typos and that sort of thing, go crazy:

function luhn(cardNumber) {
sum=0;
for(i=cardNumber.length-1;i>=0;i--) {
sum+=parseInt(cardNumber[i],10);
doubled=parseInt(cardNumber[--i],10)<<1;
sum+=doubled>9 ? doubled-9 : doubled;
}
return sum!=0 && sum%10==0;
}

The function assumes you pass in just a string of digits, no hyphens or any of that. In case the one line is confusing, most compilers will optimize an instruction like x*2 to do x<<1 instead, but I'm assuming javascript probably doesn't do that so I did it manually; it just doubles the number. You could get really crazy with the optimization, like changing parseInt(cardNumber[i],10) to cardNumber[i]-'0', but that's probably excessive.

1 comment:

Anonymous said...

Yes a nice succinct piece of code. I just added these 2 lines to provide a complete solution:
cardNumber=cardNumber.replace(/\s+/g,''); // remove white space
if (!/^\d{15,16}$/.test(cardNumber))return false; // allow 15 or 16 digits only