DEV Community

Mubeen Khan
Mubeen Khan

Posted on

Your card number has a typo detector built in, and it is 70 years old

Every time you type a 16-digit card number into a checkout form, a 70-year-old piece of arithmetic checks your typing before the number goes anywhere. It catches a mistyped digit in milliseconds, it runs entirely offline, and it was designed before the computer you are reading this on existed. It is called the Luhn algorithm, and the most surprising thing about it is how little it does.

A checksum from 1954

The algorithm was devised by Hans Peter Luhn, a scientist at IBM, who filed for a US patent on a "Computer for Verifying Numbers" on 6 January 1954 (US Patent 2,950,048, granted 23 August 1960). His problem was practical, not theoretical: identification numbers were becoming common, people transcribed them by hand, and a single wrong digit sent money or records to the wrong place. His answer was a check digit, one extra digit computed from all the digits before it, so that any single typo breaks the pattern.

That idea never went away. The same check digit sits at the end of every card number you own today, and the same test runs in every payment form, every card reader, and every validation library. It also validates IMEI numbers on phones and several national ID numbers. Seventy-plus years, zero upgrades, still catching typos.

The whole algorithm in one worked example

Take the most used test card number in the world, the Visa test card 4242 4242 4242 4242. The rule has three steps:

  1. Starting from the rightmost digit and moving left, double every second digit.
  2. If doubling gives a value over 9, subtract 9 (which is the same as adding the two digits together: 16 becomes 1 + 6 = 7).
  3. Add everything up. If the total is a multiple of 10, the number passes.

Here is the Visa test card, worked out by hand:

Digit (left to right) 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2
Doubled? Yes No Yes No Yes No Yes No Yes No Yes No Yes No Yes No
Counts as 8 2 8 2 8 2 8 2 8 2 8 2 8 2 8 2

The eight 4s are doubled to eight 8s, worth 64. The eight 2s are untouched, worth 16. Total: 64 + 16 = 80. And 80 is a multiple of 10, so the number passes.

Now change one digit, any digit. Change the last 2 to a 1 and the total becomes 79, which is not a multiple of 10, so it fails. In fact, for this number, all 144 possible single-digit substitutions fail the check. That is the whole trick: the check digit is chosen so that the total lands exactly on a multiple of 10, and almost any single-digit mistake knocks it off.

Why doubling catches typos

A plain digit sum would not work. Add up the digits of 4242 4242 4242 4242 and you get 48; swap two digits and the sum stays 48, so a transposition would slip through. Doubling every second digit breaks that symmetry: swapping two adjacent digits changes the total unless the digits are equal, which is why Luhn catches nearly all adjacent transpositions too.

The "subtract 9" step looks odd until you see what it does. Doubling 8 gives 16, and 1 + 6 = 7, which is the same as 16 - 9. So doubling with digit-summing is exactly "double, then subtract 9 if the result is over 9". It keeps every contribution a single digit, which is what makes the total a clean multiple of 10 when the number is right.

The code is ten lines

function luhnCheck(number) {
  const digits = number.replace(/\D/g, "");
  let sum = 0;
  for (let i = digits.length - 1, pos = 1; i >= 0; i--, pos++) {
    let d = Number(digits[i]);
    if (pos % 2 === 0) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return { sum, valid: sum % 10 === 0 };
}

luhnCheck("4242424242424242"); // { sum: 80, valid: true }
luhnCheck("4242424242424241"); // { sum: 79, valid: false }
luhnCheck("378282246310005");  // { sum: 60, valid: true }
Enter fullscreen mode Exit fullscreen mode

Two details worth noting. First, the loop counts positions from the right, and the check digit itself (position 1) is never doubled. Second, stripping non-digits first means spaces and hyphens are display only, so 3782 822463 10005 validates exactly like 378282246310005. The first digits also say which network issued the card: 4 is Visa, 51 to 55 or 2221 to 2720 is Mastercard, 34 or 37 is American Express, and the network fixes the length rules, which is why Amex numbers have 15 digits and a 4-digit security code while the rest use 3 digits.

What a pass does NOT prove

Here is the part most validators leave out, and it matters. A pass means the number is correctly formed, nothing more. It does not prove the card is real, active, funded, or issued. A random 16-digit number passes Luhn about 1 time in 10, because for any fixed first 15 digits exactly one of the ten possible check digits makes the total a multiple of 10. So a random guess has a 10 percent chance of looking valid, and only the issuing bank can confirm a card is real.

That is also why a validator should never ask for an expiry date or a security code, and why you should never type a real card number into a site you do not trust. Use the publishers' public test numbers instead: Visa 4242 4242 4242 4242, Mastercard 5555 5555 5555 4444, Amex 3782 822463 10005, Discover 6011 1111 1111 1117, JCB 3566 0020 2036 0505. If you want to see the Luhn working digit by digit for any of these, with the network detection and the bulk mode for up to 100 numbers, the free validator on UtilityHub shows all of it, entirely in your browser: https://www.theutilityhub.online/tools/credit-card-validator

The rule to take with you

Luhn is not security and it was never meant to be. It is error detection, built for a world of hand-copied numbers, and it survives because it solves exactly one problem perfectly: did a human type this number correctly? Whenever you build a form that takes a long number, a check digit is the cheapest validation you can add. Ten lines of code, no network call, and your users find out about the typo before the form submits instead of after the payment fails.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The worked example with 4242 4242 4242 4242 is doing more work than it looks like, because that card is almost too friendly — every doubled 4 becomes 8 and every untouched 2 stays 2, so the arithmetic hides the interesting edge. The "subtract 9" step is where the algorithm earns its keep: doubling 8 gives 16, and 1 + 6 = 7, which is exactly the same as 16 - 9, so the check stays a digit sum instead of a two-digit sum.

One blind spot worth naming for readers who will now trust the check a little too much: Luhn catches every single-digit error and most adjacent transpositions, but not 09 swapped to 90. Doubling 9 gives 18, which collapses back to 9, and 0 stays 0 either way, so the total never moves. It is a neat reminder that the algorithm was designed for the typos humans actually made on paper forms in 1954, not for adversarial input.

And your "what a pass does NOT prove" section deserves the last word: since any Luhn-valid number is trivial to generate, a passing number proves formatting and nothing else. Do you warn people on your validator tool not to paste a real card number into it, or is that a gap you are planning to close?