Credit Card Number Validation
Validates Visa, Mastercard, American Express, and Discover card numbers (digits only, no spaces).
/^(?: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})$/How it works
This pattern checks the card number prefix and length for the four major card networks: Visa (starts with 4, 13 or 16 digits), Mastercard (starts with 51–55, 16 digits), Amex (starts with 34 or 37, 15 digits), and Discover (starts with 6011 or 65, 16 digits). Always combine with a Luhn algorithm check for real validation.
Test Cases
Should Match
- 4111111111111111
- 5500005555555559
- 378282246310005
Should NOT Match
- 1234567890123456
- 411111111111
- 4111 1111 1111 1111
Quick Summary
Validates credit card numbers for Visa, Mastercard, Amex, and Discover by checking prefix and length. Strip spaces and dashes before applying. Always combine with a Luhn algorithm check, regex alone cannot detect invalid card numbers.
Key Takeaways
- Checks card network prefix and digit count, not cryptographic validity
- Must be combined with Luhn algorithm check for real card number validation
- Strip all spaces and dashes before applying this pattern
- Never log or store raw card numbers, use a PCI-compliant tokenization service
When to use it
- Client-side format validation before submitting to a payment processor
- Detecting card type to show the correct card logo in a payment form
- Sanitizing test data in development environments
Common Mistakes
- Using regex as the only validation, always run the Luhn check too
- Storing or logging card numbers, this is a PCI DSS violation
- Not stripping spaces/dashes from user input before matching
Credit Card Number Validation, Frequently Asked
What is the Luhn algorithm?
The Luhn algorithm is a checksum formula used to validate credit card numbers. It detects single-digit errors and most transposition errors. Implement it alongside this regex.
Should I validate card numbers myself?
For production payments, use a PCI-compliant processor like Stripe or Braintree. They handle validation, tokenization, and compliance for you.