typescript 26 lines · 7 steps

Validating card numbers with the Luhn check

How the Luhn algorithm verifies a credit card number by weighting alternate digits and testing the sum modulo 10.

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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing input before validation lets you accept human-friendly formatting like spaces and dashes.
  2. 2The Luhn checksum catches most single-digit typos and transpositions cheaply, without any network call.
  3. 3Doubling alternate digits and subtracting 9 keeps each contribution to a single digit's worth of value.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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