Understanding the Luhn Algorithm: Credit Card Validation Explained
Learn how the Luhn algorithm works for validating credit cards, IMEI numbers, and identification numbers. Complete guide with code examples.
Understanding the Luhn Algorithm: Credit Card Validation Explained
The Luhn algorithm, also known as the "modulus 10" algorithm, is a simple checksum formula used to validate identification numbers like credit cards, IMEI numbers, and various national IDs. This guide explains how it works and how to implement it.
What is the Luhn Algorithm?
Created by IBM scientist Hans Peter Luhn in 1954, the algorithm was designed to protect against accidental errors, not malicious attacks. It catches:
- Single digit errors (99.9% detection rate)
- Adjacent transposition errors (97.8% detection rate)
Important: Luhn validation doesn't verify that a card is real or has funds—it only checks mathematical validity.
How the Algorithm Works
Step-by-Step Process
- Start from the right - work from the rightmost digit (check digit) to the left
- Double every second digit - starting from the second-to-last digit
- Subtract 9 from doubled values > 9 - or sum the digits (same result)
- Sum all digits - add all the resulting values
- Check divisibility - if the sum is divisible by 10, the number is valid
Example: Validating 4539578763621486
Original: 4 5 3 9 5 7 8 7 6 3 6 2 1 4 8 6
Position: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Double alternating (from right, every 2nd):
8 5 6 9 10 7 16 7 12 3 12 2 2 4 16 6
Subtract 9 if > 9:
8 5 6 9 1 7 7 7 3 3 3 2 2 4 7 6
Sum: 8+5+6+9+1+7+7+7+3+3+3+2+2+4+7+6 = 80
80 % 10 = 0 ✓ Valid!
Code Implementation
JavaScript
function luhnValidate(number) {
const digits = String(number).replace(/\D/g, '').split('').map(Number);
let sum = 0;
for (let i = digits.length - 1; i >= 0; i--) {
let digit = digits[i];
// Double every second digit from right
if ((digits.length - i) % 2 === 0) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
return sum % 10 === 0;
}
// Generate check digit
function luhnCheckDigit(partialNumber) {
const digits = String(partialNumber).replace(/\D/g, '').split('').map(Number);
digits.push(0); // Placeholder
let sum = 0;
for (let i = digits.length - 1; i >= 0; i--) {
let digit = digits[i];
if ((digits.length - i) % 2 === 0) {
digit *= 2;
if (digit > 9) digit -= 9;
}
sum += digit;
}
return (10 - (sum % 10)) % 10;
}
// Examples
console.log(luhnValidate('4539578763621486')); // true
console.log(luhnValidate('4539578763621487')); // false
console.log(luhnCheckDigit('453957876362148')); // 6
Python
def luhn_validate(number):
digits = [int(d) for d in str(number) if d.isdigit()]
total = 0
for i, digit in enumerate(reversed(digits)):
if i % 2 == 1: # Every second digit from right
digit *= 2
if digit > 9:
digit -= 9
total += digit
return total % 10 == 0
# Examples
print(luhn_validate('4539578763621486')) # True
print(luhn_validate('79927398713')) # True (Wikipedia example)
Where Luhn is Used
Credit/Debit Cards
All major card networks use Luhn:
- Visa: Starts with 4, 16 digits
- Mastercard: Starts with 51-55 or 2221-2720, 16 digits
- American Express: Starts with 34/37, 15 digits
- Discover: Starts with 6011/65, 16 digits
Other Applications
- IMEI numbers: Mobile device identifiers
- Canadian Social Insurance Numbers
- Some national ID numbers
- Tracking numbers (UPS, FedEx)
Common Mistakes to Avoid
- Don't use for security - Luhn is for error detection, not fraud prevention
- Don't store API keys/passwords with only Luhn validation
- Always strip non-digits before validation
- Remember direction matters - process right to left
Test Card Numbers
Payment processors provide test numbers for development:
| Provider | Test Number | Type |
|---|---|---|
| Stripe | 4242424242424242 | Visa |
| PayPal | 4111111111111111 | Visa |
| Stripe | 5555555555554444 | Mastercard |
| Stripe | 378282246310005 | Amex |
Try Our Tools
Validate and generate Luhn numbers with our free tools:
- Luhn Validator - Check if numbers pass Luhn validation
- Credit Card Generator - Generate test card numbers
Conclusion
The Luhn algorithm is a simple but effective way to catch data entry errors. While it's not a security measure, it's an essential first-line validation for credit cards and similar identifiers. Implement it as part of your validation pipeline, but always verify with the actual issuer for real transactions.