JavaScript Credit Card Validation
Posted by Alistair Macdonald
I was reading 2600 on the bus recently and came across a credit generation algorithms which got me thinking… if you are building a web application that charges credit cards, at which point would card validation make most sense? I came to the conclusion that an efficient system, would check the credit card number was valid on the client side. This way there is little-to-no network traffic containing invalid card numbers.
Checking credit card numbers is actually pretty simple. Most services will use something called a Luhn Check, which multiplies odd indices by two, sums their digits and then divides the total sum by ten. If the result of the sum % 10 == 0 then the card number is ‘likely’ to be valid.
I came up with a a short function to validate credit card numbers passed as Strings or Floats.
var cardValid = function( cardNo ){
var sum = 0, iNum;
for( var i in cardNo+='' ){
iNum = parseInt(cardNo[i]);
sum += i%2?iNum:iNum>4?iNum*2%10+1:iNum*2;
}
return !(sum%10);
};
To use this function, just call cardValid( cardNo ) which will return either true or false.