How to Validate a Credit Card with Luhn
Validate credit card numbers with the Luhn algorithm and a brand regex, so typos are caught before the payment gateway and the brand is shown inline.
On this page
Introduction
The hardest part of catch card number typos is not writing the code — it is deciding what the code is allowed to reject. A Luhn algorithm setup that accepts everything is easy to ship and expensive to operate, because every malformed input becomes a production surprise. The discipline is to enumerate the shapes the system actually receives, encode them in Luhn algorithm, and let the library reject the rest loudly. This keeps the happy path fast and the failure path visible.
Luhn algorithm earns its place when catch card number typos is the bottleneck the user feels. Before that, it is overhead that slows the common case to protect a rare one. Measure the rejection rate and the tail latency, then decide whether the guard is worth its cost. A guard that never fires is a guard you can remove; a guard that fires constantly is a signal that the producer contract is wrong, not that the guard is too strict.
The sections below walk through the concrete decisions: where to put the luhn algorithm check, how to keep it fast under load, what to do when the contract changes, and how to test the failure paths so they degrade on purpose instead of by accident.
Strip non-digits
Strip non-digits is the first decision because it determines what the rest of the Luhn algorithm pipeline can assume. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Strip non-digits is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
function luhn(s) {
let sum = 0, alt = false;
for (let i = s.length - 1; i >= 0; i--) {
let n = +s[i]; if (alt) { n *= 2; if (n > 9) n -= 9; }
sum += n; alt = !alt;
}
return sum % 10 === 0;
}
The javascript above is the shape to ship for catch card number typos. It is small enough to audit and specific enough that the failure behavior is obvious. Adapt the constants to your traffic and latency budget, and resist the urge to handle cases the system has not seen yet.
Run the Luhn check
The mechanism behind Run the Luhn check is straightforward in Luhn algorithm, but the consequences ripple. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Run the Luhn check is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Detect the brand
Detect the brand is where most Luhn algorithm implementations leak performance. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Detect the brand is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
test('validates a known good number', () => {
expect(luhn('4111111111111111')).toBe(true);
expect(luhn('4111111111111112')).toBe(false);
});
Pin the behavior with this test. A Luhn algorithm setup that passes this test degrades on purpose instead of by accident, which is the difference between a managed failure and an incident.
Show brand icon
The hard part of Show brand icon is not the happy path — it is what happens when luhn algorithm fails halfway. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Show brand icon is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Reject on fail
Reject on fail should be observable without a debugger. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Reject on fail is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Test valid and invalid numbers
Test valid and invalid numbers is a trade, not a winner. A wrong choice here turns into catch card number typos under load, and the invariant you thought Luhn algorithm guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Test valid and invalid numbers is the one most teams skip: drive luhn algorithm to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Common pitfalls
The common pitfalls in catch card number typos all reduce to one mistake: treating Luhn algorithm as a formality instead of a contract. The contract is the thing the rest of the system relies on, and a weak contract propagates weakness everywhere.
- Skipping the luhn algorithm boundary so catch card number typos enters unvalidated.
- Assuming Luhn algorithm is fast without measuring the tail latency under load.
- Letting catch card number typos fail silently instead of failing loudly with a metric.
- Testing only the happy path so the luhn algorithm failure surfaces in production.
- Sharing mutable state across requests so one bad input poisons the next.
Conclusion
Do not conflate the conclusion with the implementation. They look similar from the outside but the failure modes differ: Luhn algorithm fails fast and the caller knows, while an unchecked path fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site.
Self-check: write a test that drives luhn algorithm to the failing condition and assert the system degrades gracefully. Then catch card number typos is a property you maintain, not a feature you hope for.
Sources: Luhn algorithm, PCI DSS
FAQ
- Is Luhn enough for security?
- No. It catches typos, not fraud. Always tokenize at the gateway and never store the PAN.
- How detect the brand?
- Match the leading digits: 4 is Visa, 5[1-5] is Mastercard, 3[47] is Amex.
Report a problem with this articleOpens a pre-filled issue on GitHub.