javascript 26 lines · 7 steps

Validating card numbers with Luhn

How the Luhn checksum verifies a credit card number by doubling alternate digits and testing divisibility by ten.

Explained by highlit
1function isValidCardNumber(input) {
2 const digits = String(input).replace(/[\s-]/g, '');
3 
4 if (!/^\d{13,19}$/.test(digits)) {
5 return false;
6 }
7 
8 let sum = 0;
9 let double = false;
10 
11 for (let i = digits.length - 1; i >= 0; i--) {
12 let digit = digits.charCodeAt(i) - 48;
13 
14 if (double) {
15 digit *= 2;
16 if (digit > 9) {
17 digit -= 9;
18 }
19 }
20 
21 sum += digit;
22 double = !double;
23 }
24 
25 return sum % 10 === 0;
26}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1The Luhn algorithm catches most single-digit typos and adjacent transpositions cheaply, which is why cards use it.
  2. 2Doubling a digit and subtracting 9 when it exceeds 9 is a shortcut for summing the digits of the doubled value.
  3. 3Structural validation like length and format should run before the expensive checksum math.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating card numbers with Luhn — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code