Major credit card issuing networks (including Visa, MasterCard, Discover, and American Express) allow simple credit card number validation using the Luhn Algorithm (also called the “modulus 10” or “mod 10” algorithm). The following code demonstrates an implementation in SAS. The code also validates the credit card number by length and by checking against a short of known test account numbers.
data eft_valid eft_invalid; input acct_nbr $ 1-30; length AddIt $2; /* check length for Visa/Discover/MC/Amex */ if length(acct_nbr) not in (15,16) then do; put 'WARNING: Not 15/16 digits: ' acct_nbr=; output eft_invalid; /* to stop processing, uncomment out the delete statement */ /* delete;*/ end; /* check for known test credit card number accounts */ /* reference: https://www.paypal.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm */ if acct_nbr in ( '378282246310005' '371449635398431' '378734493671000' '6011111111111117' '6011000990139424' '5555555555554444' '5105105105105100' '4111111111111111' '4012888888881881' '4222222222222') then do; put 'WARNING: test credit card number: ' acct_nbr=; output eft_invalid; /* to stop processing, uncomment out the delete statement */ /* delete;*/ end; /* Luhn algorithm (also called modulus 10 or mod 10) */ /* mostly copied from Patrick http://support.sas.com/forums/thread.jspa?threadID=4274 */ ChkSum = 0; /* reset */ ChkStr=left(reverse(acct_nbr)); do pos=1 to length(ChkStr); if mod(pos,2) then /* odd positions */ do; AddIt=substr(ChkStr,pos,1); end; else /* even positions: digit*2 */ do; AddIt=put(2*input(substr(ChkStr,pos,1),2.),2.); end; /* add digits */ do i=1 to length(AddIt); ChkSum+input(substr(AddIt,i,1),2.); end; end; /* Check if ID is valid or not (if ChkSum ends with Zero) */ if mod(ChkSum,10)=0 then do; put 'NOTE: This is a valid ID: ' acct_nbr= ChkSum=; output eft_valid; end; else if mod(ChkSum,10) ne 0 then do; put 'WARNING: This is a invalid ID: ' acct_nbr= ChkSum=; output eft_invalid; end; drop ChkSum i pos ChkStr AddIt; datalines; 378282246310005 371449635398431 378734493671000 6011111111111117 6011000990139424 5555555555554444 5105105105105100 4111111111111111 4012888888881881 4222222222222 123456789 3847592 48573726264859560 2843759 00028434305834 442308239586 ; run;
Patrick’s SAS code was very helpful, but without resetting ChkSum, SAS would fail all credit card numbers following an invalid card number.
This code was executed on 177,172 credit card records and found only 40 invalid numbers. Most of them were obvious like 4000000000000000. YMMV.
This code was tested with SAS 9.3 64-bit on Windows 7.
UPDATE December 5, 2013: Test credit card numbers and the link to Paypal were fixed.
This is the only code written in SAS which I could find easily for the Luhn Algorithm.
Many thanks.
Thanks for sharing this! It helped me to build a similar example for validating NPI (National Provider ID) values. I lifted your algorithm code, but wrapped it in FCMP so that it works like a SAS function.