Validate a credit card number with regex in JavaScript
Advanced · 4 min read
Every checkout page that takes a card number checks it before sending it anywhere. If you type one digit wrong, the form tells you straight away instead of waiting for the bank to say no. In this tutorial you will build that check in JavaScript.
There are two parts. A regular expression tells you the card's brand (Visa, Mastercard and so on) from its first digits and its length. A small sum called the Luhn checksum catches typos, which no pattern can do. You need to know loops, if and the basics of /.../.test(). Everything else is explained as we go.
What a pattern can and can't see
A regular expression only sees the shape of text: which characters, in what order, how many. 4111 1111 1111 1111 and 4111 1111 1111 1112 have the same shape: sixteen digits starting with a 4. Only one of them is a valid card number. To tell them apart you need arithmetic.
The Luhn checksum in plain words
Card numbers are built so their digits add up in a special way. Starting from the rightmost digit:
- Keep the first digit as it is, double the second, keep the third, double the fourth, and so on.
- If doubling gives more than 9, subtract 9 (so 16 becomes 7).
- Add everything up. A valid number gives a total that divides evenly by 10.
number: 7 9 9 2 7 3 9 8 7 1 3
from right: 3 1 7 8 9 3 7 2 9 9 7
doubled? - x - x - x - x - x -
becomes: 3 2 7 7 9 6 7 4 9 9 7 total 70, divides by 10: valid
Change any single digit and the total changes, so the check fails. That is why it catches typos.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
2 Check a credit card number
hardCheck a card number. A pattern can identify the brand; use the checksum that actually detects typos as well.
Stuck? Three hints, smallest first
- 1. The Luhn algorithm: double every second digit from the right, subtract 9 if over 9, and the total must divide by 10.
- 2. Brand prefixes differ in length: Visa starts 4, Mastercard 51–55 or 2221–2720, Amex 34 or 37.
- 3. Strip spaces and dashes before doing anything. People type them.
Step 1: clean up what people type
People type card numbers with spaces or dashes. Remove them first. \s means "any whitespace character", [\s-] means "whitespace or a dash", and the g flag means "every match, not just the first":
const digits = '4111 1111-1111 1111'.replace(/[\s-]/g, '');
console.log(digits); // '4111111111111111'
console.log(/^\d+$/.test(digits)); // true
console.log(/^\d+$/.test('4111a')); // false
\d means "one digit" and + means "one or more". With ^ at the start and $ at the end, /^\d+$/ says "digits from start to finish, nothing else".
Step 2: write the Luhn checksum
[...digits].reverse() gives the digits from the right. forEach hands us each digit and its position i. Positions 1, 3, 5 and so on are the ones to double:
function luhnValid(input) {
const digits = input.replace(/\D/g, '');
if (digits.length < 12) return false;
let sum = 0;
[...digits].reverse().forEach((char, i) => {
let n = Number(char);
if (i % 2 === 1) { n *= 2; if (n > 9) n -= 9; }
sum += n;
});
return sum % 10 === 0;
}
console.log(luhnValid('4111111111111111')); // true
console.log(luhnValid('4111111111111112')); // false: one digit changed
\D (capital D) is the opposite of \d: "anything that is not a digit". Removing those is another way to clean the input. The length guard refuses numbers too short to be a card.
Step 3: find the brand with a pattern
Each card network owns certain starting digits. Visa numbers start with 4 and have 13, 16 or 19 digits. \d{12} means "exactly twelve digits", and (\d{3})? means "maybe three more":
const VISA = /^4\d{12}(\d{3})?(\d{3})?$/;
const AMEX = /^3[47]\d{13}$/;
console.log(VISA.test('4111111111111111')); // true
console.log(AMEX.test('378282246310005')); // true
console.log(VISA.test('4111111111111112')); // true: the shape is fine
That last line is the point of this whole exercise. The pattern happily accepts a mistyped number. American Express starts with 34 or 37 (3[47]) and has 15 digits.
Step 4: put the pieces together
The answer keeps a list of brands, each with a name and a pattern, and find picks the first one that matches. Then the order of checks gives the user a helpful reason:
const BRANDS = [
{ name: 'Visa', pattern: /^4\d{12}(\d{3})?(\d{3})?$/ },
{ name: 'American Express', pattern: /^3[47]\d{13}$/ },
];
function luhnValid(digits) {
let sum = 0;
[...digits].reverse().forEach((char, i) => {
let n = Number(char);
if (i % 2 === 1) { n *= 2; if (n > 9) n -= 9; }
sum += n;
});
return digits.length >= 12 && sum % 10 === 0;
}
function checkCard(input) {
const digits = String(input).replace(/[\s-]/g, '');
if (!/^\d+$/.test(digits)) return { ok: false, why: 'digits, spaces and dashes only' };
const brand = BRANDS.find((b) => b.pattern.test(digits));
if (!luhnValid(digits)) return { ok: false, why: 'checksum failed', brand: brand?.name ?? null };
if (!brand) return { ok: false, why: 'unknown network', brand: null };
return { ok: true, brand: brand.name };
}
console.log(checkCard('4111 1111 1111 1111').ok); // true
console.log(checkCard('4111 1111 1111 1112').why); // 'checksum failed'
brand?.name ?? null reads the name if a brand was found, and gives null if not. The full answer also has Mastercard, Discover and Diners Club, and longer messages.
The full solution
The panel runs the complete checker on published test numbers (none of them is a real account) plus one with a changed digit. Press Run and watch the changed digit get caught while its brand is still named.
// The checksum. This is the part that catches a mistyped digit; a regex cannot.
function luhnValid(input) {
const digits = input.replace(/\D/g, '');
if (digits.length < 12) return false;
let sum = 0;
[...digits].reverse().forEach((char, i) => {
let n = Number(char);
if (i % 2 === 1) { n *= 2; if (n > 9) n -= 9; }
sum += n;
});
return sum % 10 === 0;
}
// The brand, from the prefix and length. Shape only: it says which network the
// number belongs to, not that the card exists.
const BRANDS = [
{ name: 'Visa', pattern: /^4\d{12}(\d{3})?(\d{3})?$/ },
{ name: 'Mastercard', pattern: /^(5[1-5]\d{14}|2(22[1-9]|2[3-9]\d|[3-6]\d\d|7[01]\d|720)\d{12})$/ },
{ name: 'American Express', pattern: /^3[47]\d{13}$/ },
{ name: 'Discover', pattern: /^6(?:011|5\d{2})\d{12}$/ },
{ name: 'Diners Club', pattern: /^3(?:0[0-5]|[68]\d)\d{11}$/ },
];
function checkCard(input) {
const digits = String(input).replace(/[\s-]/g, '');
if (!/^\d+$/.test(digits)) return { ok: false, why: 'digits, spaces and dashes only' };
const brand = BRANDS.find((b) => b.pattern.test(digits));
if (!luhnValid(digits)) return { ok: false, why: 'the checksum does not match: check for a typo', brand: brand?.name ?? null };
if (!brand) return { ok: false, why: 'the checksum passes but the prefix matches no known network', brand: null };
return { ok: true, brand: brand.name };
}
// Standard published test numbers. None of these is a real account.
const samples = [
'4111 1111 1111 1111',
'5500 0055 5555 5559',
'3782 822463 10005',
'6011 1111 1111 1117',
'3056 930902 5904',
'4111 1111 1111 1112', // one digit changed
];
for (const s of samples) {
const r = checkCard(s);
console.log(s.padEnd(22), r.ok ? `ok, ${r.brand}` : `refused: ${r.why}`);
}
console.log('a single transposed digit is caught:', checkCard('4111111111111121').ok);
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a valid Visa passes', checkCard('4111 1111 1111 1111'), { ok: true, brand: 'Visa' });
test('a valid Mastercard', checkCard('5500 0055 5555 5559').brand, 'Mastercard');
test('a valid Amex', checkCard('3782 822463 10005').brand, 'American Express');
test('a valid Discover', checkCard('6011 1111 1111 1117').brand, 'Discover');
test('a valid Diners Club', checkCard('3056 930902 5904').brand, 'Diners Club');
test('spaces are ignored', checkCard('4111111111111111').ok, true);
test('dashes are ignored too', checkCard('4111-1111-1111-1111').ok, true);
test('one changed digit fails the checksum', checkCard('4111 1111 1111 1112').ok, false);
test('and the reason says so', checkCard('4111 1111 1111 1112').why.includes('checksum'), true);
test('but the brand is still identified', checkCard('4111 1111 1111 1112').brand, 'Visa');
test('letters are refused', checkCard('4111 1111 1111 111a').ok, false);
test('an empty string is refused', checkCard('').ok, false);
test('the Luhn check alone rejects a bad number', luhnValid('4111111111111112'), false);
test('and accepts a good one', luhnValid('4111111111111111'), true);
test('a transposed pair is caught', checkCard('4111111111111121').ok, false);
test('the checksum cannot catch every transposition, though', luhnValid('4111111111111111') === luhnValid('4111111111111111'), true);
The Luhn checksum is the real content here. A regex can confirm a number is sixteen digits starting with a 4; only the checksum notices that one of them is wrong, and the assertions show a single changed digit being caught. Every card network uses it, and it is what stops a mistyped number reaching a payment processor.
Be clear about what it is not. Luhn detects all single-digit errors and most transpositions, but it is a typo check, not authentication — a number that passes may be closed, expired, or invented. The prefix patterns tell you the network, and those ranges change: Mastercard's 2221–2720 block was added in 2017, so any pattern written before then rejects valid cards.
All the numbers above are published test numbers, not real accounts. And in real work, do not build this: use the payment provider's client library, so a card number never touches your server.
Common mistakes
- Trusting the pattern alone. It checks the shape, so a mistyped number with the right length passes. The checksum is what catches the typo.
- Doubling from the left. Luhn counts from the rightmost digit. For a 15-digit Amex number, counting from the left doubles the wrong digits.
- Thinking a valid checksum means a real card. It only means no typo was found. The card could be expired, closed or made up.
Try it yourself
- Add a brand to
BRANDSfor Mastercard numbers starting 51 to 55:/^5[1-5]\d{14}$/. - Write
formatCard(digits)that puts a space after every four digits. (Hint:replace(/(\d{4})(?=\d)/g, '$1 ').) - Run
luhnValidon'4111111111111121', which swaps two digits. Is the swap caught?