Skip to content

Regex for Credit Card Number

This regex matches major credit card number formats including Visa, Mastercard, American Express, Diners Club, Discover, and JCB. Each card type has a distinct prefix and length, and this pattern validates the correct prefix-length combinations. Note that this only checks the format, not the Luhn checksum or whether the card is actually valid or active.

Pattern
^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$
Test this pattern in the Regex Tester →

What is the regex pattern for Credit Card Number?

The regex pattern for Credit Card Number is ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$. This regex matches major credit card number formats including Visa, Mastercard, American Express, Diners Club, Discover, and JCB. Each card type has a distinct prefix and length, and this pattern validates the correct prefix-length combinations. Note that this only checks the format, not the Luhn checksum or whether the card is actually valid or active. This pattern is commonly used for payment form validation and card type detection.

Test Examples

Match
4111111111111111
Matches: 4111111111111111
Match
5500000000000004
Matches: 5500000000000004
Match
371449635398431
Matches: 371449635398431

Common Uses

Variations

Visa only

^4[0-9]{12}(?:[0-9]{3})?$

Starts with 4, 13 or 16 digits

Mastercard only

^5[1-5][0-9]{14}$

Starts with 51-55, 16 digits

With spaces/dashes

^(?:4[0-9]{3}|5[1-5][0-9]{2}|3[47][0-9]{2})[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}$

Allows optional spaces or dashes between groups

Frequently Asked Questions

Does this regex validate the credit card number?

No, it only validates the format and card type prefix. A valid credit card number must also pass the Luhn algorithm checksum. Always use the Luhn check in addition to regex for payment validation.

How do I determine the card type from the number?

Visa starts with 4, Mastercard with 51-55, American Express with 34 or 37, Discover with 6011 or 65, and JCB with 2131, 1800, or 35. The prefix determines the card network.

Should I store credit card numbers?

Never store full credit card numbers unless you are PCI DSS compliant. Use a payment processor like Stripe or Braintree that handles card storage securely, and only store the last four digits for display.

Related Patterns

US Social Security Number

^(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!...

US Phone Number

^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\...

US ZIP Code

^\d{5}(-\d{4})?$

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →