What Is a Good Regex for Credit Card Number Validation?
Pattern: ^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|3[47]\d{13}|6(?:011|5\d{2})\d{12})$. Credit card numbers follow specific formats based on the card network. Visa starts with 4, Mastercard with 51-55, Amex with 34/37, and Discover with 6011/65. This regex validates the basic format but does not perform the Luhn checksum. Always combine format validation with the Luhn algorithm.
Breaking Down the Pattern
| Part | Meaning |
|---|---|
4[0-9]{12}(?:[0-9]{3})? | Visa: starts with 4, 13 or 16 digits |
5[1-5][0-9]{14} | Mastercard: starts with 51-55, 16 digits |
3[47][0-9]{13} | Amex: starts with 34 or 37, 15 digits |
6(?:011|5[0-9]{2})[0-9]{12} | Discover: starts with 6011 or 65, 16 digits |
Test Cases
| Input | Match? | Note |
|---|---|---|
4111111111111111 | Yes | Valid format |
5500000000000004 | Yes | Valid format |
371449635398431 | Yes | Valid format |
1234567890123456 | No | Does not start with a valid card prefix |
411111111111 | No | Only 12 digits (Visa requires 13 or 16) |
Usage Examples
JavaScript
const pattern = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$/;
pattern.test('4111111111111111'); // true
pattern.test('1234567890123456'); // false
Python
import re
pattern = r'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$'
bool(re.match(pattern, '4111111111111111')) # True
bool(re.match(pattern, '1234567890123456')) # False
Common Pitfalls
- Regex only validates the format. Always use the Luhn algorithm to verify the check digit.
- Never store or log credit card numbers in plain text -- this violates PCI DSS.
- Modern Mastercard numbers also start with 2221-2720, which this basic pattern does not cover.
- Always strip spaces and hyphens before validation (users often enter "4111 1111 1111 1111").
Try It Yourself
Test this regex with our Regex Tester.
Frequently Asked Questions
What is the Luhn algorithm?
The Luhn algorithm (mod 10) is a checksum formula used to validate credit card numbers. It catches most single-digit errors and transposition errors. Every valid credit card number passes the Luhn check.
Is it safe to validate credit cards with client-side regex?
For format hints (showing a Visa/Mastercard icon), yes. For actual payment processing, always validate server-side and use a PCI-compliant payment processor like Stripe. Never handle raw card numbers yourself.
Why do test card numbers like 4111111111111111 work?
Payment processors provide specific test numbers that pass the Luhn check but are reserved for testing. They are never charged. 4111111111111111 is the standard Visa test number.