Credit/Debit Card Number Validation Regular Expression
A valid credit or debit card number follows specific patterns defined by card issuers. This regex validates the format of major card types including Visa, Mastercard, American Express, Discover, Diners Club, and JCB based on their IIN (Issuer Identification Number) ranges and length requirements. Card numbers should be validated without spaces or dashes. Credit card numbers are a specialized type of number pattern.
Recommended Solution
Explanation
^- Start of the string.4[0-9]{12}(?:[0-9]{3})?- Visa: Starts with 4, followed by 12 or 15 more digits (13 or 16 total).5[1-5][0-9]{14}- Mastercard: Starts with 51-55, followed by 14 more digits (16 total).3[47][0-9]{13}- American Express: Starts with 34 or 37, followed by 13 more digits (15 total).3(?:0[0-5]|[68][0-9])[0-9]{11}- Diners Club: Starts with 300-305, 36, or 38, followed by 11 more digits (14 total).6(?:011|5[0-9]{2})[0-9]{12}- Discover: Starts with 6011 or 65, followed by 12 more digits (16 total).(?:2131|1800|35\d{3})\d{11}- JCB: Starts with 2131, 1800, or 35, followed by appropriate digits (15-16 total).$- End of the string.
Notes
- This regex validates the format and IIN ranges but does NOT perform Luhn algorithm validation.
- For production use, implement the Luhn algorithm (checksum validation) in addition to format validation.
- This regex expects card numbers without spaces, dashes, or other separators. Preprocess input to remove formatting.
- Card number formats can change as issuers introduce new IIN ranges. Keep patterns updated.
- Never log, store, or transmit card numbers in plain text. Follow PCI DSS compliance standards.
Implementation
Test Cases
| Card Number | Type/Note | Valid |
|---|---|---|
| 4532015112830366 | Visa (16 digits) | |
| 4532015112830 | Visa (13 digits) | |
| 5425233430109903 | Mastercard | |
| 374245455400126 | American Express | |
| 371449635398431 | American Express | |
| 6011111111111117 | Discover | |
| 6011000990139424 | Discover | |
| 3056930902595100 | Diners Club | |
| 36227206271667 | Diners Club | |
| 3530111333300000 | JCB | |
| 3566002020360505 | JCB | |
| 123 | Too short | |
| 4532-0151-1283-0366 | Contains dashes | |
| 4532 0151 1283 0366 | Contains spaces | |
| 1234567890123456 | Invalid prefix | |
| 453201511283036 | Invalid length for Visa | |
| 542523343010990 | Invalid length for Mastercard | |
| 37424545540012 | Invalid length for Amex | |
| (empty string) | Empty string | |
| abcd1234efgh5678 | Contains letters |