How to validate a credit card number with Luhn algorithm?

You may have tried to pay online and came across an error, saying your credit card number is not valid. You may ask how is a card number is validated? The answer is Luhn algorithm!

Tinhinane
2 min readJul 19, 2020
Invalid card number error

Given that Primary Account Numbers (PANs, also known simply as a card number) are between 8 and 19 digits, online shoppers frequently mistype them. The Luhn algorithm, also called MOD-10 checksum, is easy to implement, it costs nothing (the algorithm is in the public domain) and it spares the gateway payment from receiving invalid card numbers. In other words, even a small e-commerce vendor can add this algorithm to its website.

⚠️ The algorithm’s purpose is to prevent accidental errors, not malicious attacks.

The basic form of the Luhn algorithm can only detect: single-digit errors, transpositions of adjacent digits (Except transposition of the two-digit sequence 06 to 60, or 60 to 06), most of twin errors (Except 22→55, 3366 or 44→77) — Twin errors are made when a pair of similar digits are replaced with another pair, that is ‘AA’ is replaced with a pair of digits ‘BB’.

Step by step implementation

Let’s consider this PAN as an example: 4–3–4–2–0–7–7–2–7–7–1–8–3–2–8–8

  • Step 1: Starting from the rightmost digit, double every second digit. The result is: 8–3–8–2–0–7–14–2–14–7–2–8–6–2–16–8
  • Step 2: If double of a digit is more than 9, add the digits. So the number will become: 8–3–8–2–0–7–5–2–5–7–2–8–6–2–7–8
  • Step 3: Sum all of the digits. If the total modulo 10 is equal to 0, then the card number is valid. The sum of all digits, in this case, is 80, and 80 mod 10 is zero, so the card number ‘4342077277183288’ is validated by the Luhn algorithm.

I’m providing below an implementation with Python.

Again, be cautious about adjacent transposition and twin errors, Luhn algorithm won’t be able to catch them all. Damm algorithm, another checksums algorithm (Not covered in this article), is capable of detecting all adjacent transposition errors.

--

--

Tinhinane

Cloud Engineering Manager in Belgium's IT Consulting Scene 🇧🇪 | Just as you wouldn't put pineapple on pizza, couscous n' merguez is a no go!