Card Validation in JavaScript Using Luhn’s Algorithm

Raphael Sani Enejo (SanRaph)
4 min readMar 30, 2022

Have you ever wondered how credit card numbers get validated whenever you use your cards with these everyday financial applications and machines like the ATM and others?
Well, most credit cards and many government identification numbers use the Luhn algorithm, it is a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. We are going to see how you can validate cards using the Luhn algorithm.

What is Luhn’s Algorithm?

Well, Wikipedia has this to say,

“The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, named after its creator, IBM scientist Hans Peter Luhn, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, Israeli ID Numbers, South African ID Numbers, Swedish National identification numbers, Swedish Corporate Identity Numbers (OrgNr), Greek Social Security Numbers (ΑΜΚΑ), SIM card numbers and survey codes appearing on McDonald’s, Taco Bell, and Tractor Supply Co. receipts. It is described in U.S. Patent №2,950,048, granted on August 23, 1960.

The algorithm is in the public domain and is in wide use today. It is specified in ISO/IEC 7812–1. It is not intended to be a cryptographically secure hash function; it was designed to protect against accidental errors, not malicious attacks.”

Example for computing check digit
Assume an example of an account number “7992739871” (just the “payload”, check digit not yet included):

This is how the algorithm works

The sum of the resulting digits is 67.

The check digit is equal to 10-(67 mod 10)=3.

This makes the full account number read 79927398713.

Example for validating check digit
1. Drop the check digit (last digit) of the number to validate. (e.g. 79927398713 -> 7992739871)
2. Calculate the check digit (see above)
3. Compare your result with the original check digit. If both numbers match, the result is valid. (e.g. (givenCheckDigit = calculatedCheckDigit)=(isValidCheckDigit).

Implementing Luhn

Javascripts’ implementation of Luhn

Let us run the code in the console, on the browser hit F12, then copy this part of the code and paste it into the console, hit enter or the return key, and that works for you, then copying that last part with the function implementation and pasting it in the console and jabbing the enter key again gives you this

Code running in console

so here is what is hapening in the code, explaining code in words can in fact seems almost impossible but I am going to help spell out what is happening in the code above.
The function takes in an array
loops through the array/digits however to do this, we need to know the array size which we get by finding the array length, we need a starting point, and the last point in our case we are decrementing because we need to start from the right.
We checked to see if the boolean variable second is true, if that is so then double the number and assign it to double. But what is double and how do we get the actual values at that index position to double? We get this by taking the array position and grabbing the values at the particular index using javascript charCodeAt() which gives us the Unicode character at the array position, remove the first (where you see ‘0’) index Unicode character from it so that we can have 0 then 1 index every time the loop steps through each index.
Sum of all the numbers plus double with the modulus of 10 and save it back to sum, but what is sum?
The variable sum is derived from the total sum plus double modulus 10 using parseInt(), the second argument is called the radix or base, in our case base 10, this is the point where we sum all the doubled numbers with two digits.
Assigning is-Second to is NOT-Second stops the search for the second values to double because if we reach here we might have got all the second values and double them so equalize the operation.

This function's entire purpose is to check if sum modulus 10 is 0, this is the main target of Luhn's algorithm, remember to define the sum with the initial value of 0.

After all these, it is time to use our Luhn function, create an array with a series of digits, run a check using if, and put the function inside feeding it the defined array, if all is well, it will console log the result else it will console log the opposite result as you choose to define it.
Luhn is truly an interesting way of validating pins and numbers that you use every day.

Conclusion
The Luhn algorithm will detect any single-digit error, as well as almost all transpositions of adjacent digits. It will not, however, detect transposition of the two-digit sequence 09 to 90 (or vice versa). for this, you can check out other more complex ones like the Verhoeff algorithm, Damm algorithm, and Luhn mod N algorithm that may better suit your needs.

Now, go be a hero by writing safer and solid financial applications that change lives. hit me up if there is anything you feel should be added or explained differently, I am open to tons of suggestions, in the spirit of oneness, happy coding mate!

--

--

Raphael Sani Enejo (SanRaph)

A Software Engineer with a strong user focus. Extensive experience in developing robust code and building world-class applications and life-changing products.