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.
^(?: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})$ 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
4111111111111111 4111111111111111 5500000000000004 5500000000000004 371449635398431 371449635398431 Common Uses
- ✓ Payment form validation
- ✓ Card type detection
- ✓ PCI compliance logging
- ✓ Data masking
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.