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
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
9 steps
typescript
interface UserAgentInfo { browser: { name: string; version: string }; os: { name: string; version: string }; device: 'mobile' | 'tablet' | 'desktop';
Parsing a user-agent string with ordered rules
regex
parsing
pattern-matching
Intermediate
9 steps
php
<?php declare(strict_types=1);
Normalizing human names in PHP
unicode
text-normalization
transliteration
Intermediate
8 steps
typescript
import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, timer, throwError } from 'rxjs'; import { switchMap, takeWhile, filter, take, catchError } from 'rxjs/operators';
Polling a job until it finishes in Angular
rxjs
polling
observables
Intermediate
7 steps
typescript
type Flatten = Record<string, unknown>; function isPlainObject(value: unknown): value is Record<string, unknown> { return (
Flattening nested objects into dotted keys
recursion
reduce
type-guards
Intermediate
7 steps
rust
use once_cell::sync::Lazy; use regex::Regex; static CREDIT_CARD: Lazy<Regex> = Lazy::new(|| {
Redacting sensitive data from logs in Rust
regex
lazy-initialization
checksum-validation
Intermediate
9 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.