How to Match Credit Card Numbers with Regex
Handling payment data securely is critical. Before sending a credit card number to a payment gateway like Stripe, you should validate its format on the client-side to prevent unnecessary API calls.
The Pattern Breakdown
This pattern relies heavily on alternation | to check the starting digits assigned to major network providers:
- Visa:
4[0-9]{12}(?:[0-9]{3})?ensures the card starts with 4 and is 13 or 16 digits long. - MasterCard:
5[1-5][0-9]{14}ensures it starts with 51-55 and is 16 digits long. - American Express:
3[47][0-9]{13}ensures it starts with 34 or 37 and is 15 digits long.
Security Warning
Regex only validates the format of the card. It does not verify if the card is active or real. Always use a LUHN algorithm check in conjunction with regex before processing.