Regex for Credit Card Number Validation: the Pattern Only Checks the Shape
Every developer has typed 4111111111111111 into a test form. It is Visa's public test number, and it passes every check below. Most tutorials skip the part that matters: a regex for credit card number validation answers one question, "does this look like a card number," and there are two more questions after it. The regex tells you the brand. The Luhn checksum tells you it is not a typo. Only the processor tells you it is real money.
Regex for credit card number validation: the four patterns
Card brands are identified by prefix and length. These four patterns cover the vast majority of cards you will see, and I tested each one against known test numbers before publishing:
Visa ^4[0-9]{12}(?:[0-9]{3})?$ # 13 or 16 digits, starts with 4
Mastercard ^5[1-5][0-9]{14}$ # 16 digits, starts 51-55
Amex ^3[47][0-9]{13}$ # 15 digits, starts 34 or 37
Discover ^6(?:011|5[0-9]{2})[0-9]{12}$ # 16 digits, 6011 / 644-649 / 65
The single most common bug is skipping the normalize step. Real users type 4532 0151 1283 0366 with spaces, and a digits-only pattern rejects it. Strip first, then match:
const clean = raw.replace(/\D/g, ""); // "4532 0151 1283 0366" -> "4532015112830366"
const brand = /^4/.test(clean) ? "visa"
: /^5[1-5]/.test(clean) ? "mastercard"
: /^3[47]/.test(clean) ? "amex"
: /^6(?:011|5)/.test(clean) ? "discover" : "unknown";
Do not solve this by loosening the pattern to accept spaces, like ^4[0-9 ]{12,16}$. That pattern also accepts sixteen spaces. Normalize first, then run the strict pattern. The second most common bug is checking only the prefix: ^4 matches a single digit 4 and a twenty-digit string alike. The full per-brand pattern enforces prefix and length, which is the entire point.
The Luhn check catches what the pattern cannot
A sixteen-digit string starting with 4 passes the Visa pattern and can still be a typo. The Luhn checksum exists for exactly this: starting from the rightmost digit, double every second digit, subtract 9 from any result over 9, add everything up. If the total divides by 10, the number is plausibly real. Change one digit of the test number and it fails:
| Input | Brand | Luhn | Verdict |
|---|---|---|---|
4111111111111111 | Visa | Pass | Valid shape |
4111111111111112 | Visa | Fail | Typo: one digit off |
5500000000000004 | Mastercard | Pass | Valid shape |
378282246310005 | Amex | Pass | Valid shape |
1234567890123456 | None | Fail | No brand, bad checksum |
The implementation is a dozen lines in any language. Here it is in Python, matching the table above:
import re
def luhn_ok(number: str) -> bool:
digits = re.sub(r"\D", "", number)
total, double = 0, False
for ch in reversed(digits):
n = int(ch)
if double:
n *= 2
if n > 9:
n -= 9
total += n
double = not double
return total % 10 == 0
The bug I see most in Luhn implementations: doubling from the left instead of the right. The rule is every second digit starting from the rightmost, and iterating the reversed string the way the snippet does makes it hard to get wrong.
One last thing, and it matters more than the regex: this whole pipeline is for catching typos in a form. Never store full card numbers you collect this way. Real charges go through a payment processor with proper tokenization. The pattern plus Luhn keeps bad input out of your form; the processor is the only thing that validates a real card.
Frequently asked questions
Can regex alone validate a credit card number?
No. Regex checks the shape: the brand prefix and the digit count. The Luhn checksum catches typos. Only the payment processor can confirm the account is real and has funds.
What is the Luhn algorithm?
A checksum used on card numbers: starting from the rightmost digit, double every second digit, subtract 9 from any result over 9, and sum everything. If the total is divisible by 10, the number passes.
Why does my card pattern fail on numbers with spaces?
Because the pattern expects digits only. Strip all non-digits first, then run a strict digits-only pattern. Never loosen the pattern to accept spaces.
Do I need to detect the card brand?
Not for validity, but it improves the form: showing the Visa or Amex logo as the user types is good UX, and brand-specific length checks catch errors earlier than a generic pattern.
Is it safe to validate card numbers in the browser?
For typo detection, yes. For anything else, no: never store full card numbers outside a PCI-DSS-compliant system. Use a payment processor like Stripe or Braintree for real charges.
Related reading: Password Strength: Regex vs zxcvbn · Regex for Postal Code Validation · Phone Number Regex vs libphonenumber
One practical regex guide a week. Get it by email.