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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing input before validation lets you accept human-friendly formatting like spaces and dashes.
- 2The Luhn checksum catches most single-digit typos and transpositions cheaply, without any network call.
- 3Doubling alternate digits and subtracting 9 keeps each contribution to a single digit's worth of value.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-card-numbers-with-the-luhn-check-explained-typescript-3707/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.