Credit Card Validation in Apex

There are requests from my blog readers asking for Credit Card Validation logic using Apex. I did some reasearch on credit card validation and found this algorithm called Luhn Algorithm which uses a simple checksum formula to validate a variety of Credit Card Numbers.

Lunh’s Algorithm

Here is the code I wrote for Credit Card Number as String input. You can also use this for Integer input with simple tweaks.

Credit Card Validation using Apex

public boolean CCValidation(String CCNumber){
Integer sum = 0;
Integer len = CCNumber.length();
for(Integer i=len-1;i>=0;i--){
Integer num = Integer.ValueOf(CCNumber.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 );
}

Advertisements

5 comments

  1. Nice and elegant. This is the most compact Lohn algorithm that I’ve found for Salesforce Apex. Thank you very much for posting this.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s