# Sunday, 21 February 2010

There are several bank specific rules for validating credit cards, but all card numbers can be validated using the Luhn algorithm. The Luhn algorithm, aka the Luhn formula or "modulus 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers.

It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks. Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from collections of random digits.

Programmers accustomed to using '%' as a modulus operator need only to shift gears slightly and use the Math.mod(int1, int2) library function when working with Apex.

public static boolean isValidCheckSum(List<integer> numbers){
	integer sum = 0;
	integer len = numbers.size();
	
	for (integer i = len - 1; i >= 0; i--)
	{
		if (math.mod(i , 2) == math.mod(len,  2) )
		{
			integer n = numbers[i] * 2;
			sum += (n / 10) + ( math.mod(n, 10));
		}
		else
			sum += numbers[i];
	}
	return ( math.mod( sum, 10) == 0 );
}
Tuesday, 18 May 2010 16:52:10 (Pacific Daylight Time, UTC-07:00)
Thanks for your example! I was pleasantly surprised to find this page linked from Wikipedia.

I've modified your script to handle string input:

public static boolean isValidCheckSum(String input) {
integer sum = 0;
integer len = input.length();
for (integer i = len - 1; i >= 0; i--)
{
integer num = Integer.valueOf(input.substring(i, i+1));
if (math.mod(i , 2) == math.mod(len, 2) )
{
integer n = num * 2;
sum += (n / 10) + ( math.mod(n, 10));
}
else
sum += num;
}
return ( math.mod( sum, 10) == 0 );
}

and some test code ;)

static testMethod void testIsValidCheckSum() {
System.assert(ValidationUtils.isValidCheckSum('49927398716')); // from http://en.wikipedia.org/wiki/Luhn_algorithm
System.assert(ValidationUtils.isValidCheckSum('8763'));
System.assert(!ValidationUtils.isValidCheckSum('1111'));
}
Tuesday, 18 May 2010 17:16:27 (Pacific Daylight Time, UTC-07:00)
Hey, that's a great enhancement. Thanks for sharing!

-Mike
Comments are closed.