🔍Regex Recipes
Credit Card Format (Luhn Disclaimer)
Match credit card number formats. WARNING: Format match only - must run Luhn algorithm separately for validation.
Pattern
^\d{13,19}$Explanation
Matches 13-19 digit numbers (covers most card types). Does NOT validate checksum - you must use Luhn algorithm separately.
Examples
Visa-length
Input
4532123456789012
Output
✓ Format match (16 digits)
Amex-length
Input
378282246310005
Output
✓ Format match (15 digits)
With spaces
Input
4532 1234 5678 9012
Output
✗ No match (contains spaces)
Code Examples
JavaScript
// Format validation only
const cardRegex = /^\d{13,19}$/;
// MUST also validate with Luhn algorithm
function luhnCheck(cardNumber) {
const digits = cardNumber.split('').map(Number).reverse();
const sum = digits.reduce((acc, digit, idx) => {
if (idx % 2 === 1) {
digit *= 2;
if (digit > 9) digit -= 9;
}
return acc + digit;
}, 0);
return sum % 10 === 0;
}
function isValidCard(input) {
const cleaned = input.replace(/\s/g, '');
return cardRegex.test(cleaned) && luhnCheck(cleaned);
}Try it Now
💡 Tips
- Always implement Luhn checksum validation
- Strip spaces/dashes before validation
- Use PCI-compliant payment processors
- Display only last 4 digits to users
- Consider card type validation if needed
⚠️ Common Pitfalls
- CRITICAL: Regex does NOT validate card number - use Luhn algorithm
- Does not identify card type (Visa, Mastercard, etc.)
- Does not handle spaces or dashes in formatted numbers
- Never log or store full card numbers