Credit card regex
Regex patterns to recognise Visa, Mastercard and American Express card numbers, plus the Luhn checksum you need alongside them.
Pattern
/^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|2(?:2[2-9][1-9]|2[3-9]\d|[3-6]\d\d|7[01]\d|720)\d{12}|3[47]\d{13})$/Matches
41111111111111115555555555554444378282246310005
Doesn't match
12345678123456784111-1111-1111-111137828224631000
Notes
- Remove spaces and dashes first: value.replace(/[\s-]/g, "").
- A matching number can still be invalid — also run the Luhn checksum. The examples above are the standard test numbers published by payment processors.
- Handle real card data only through your payment provider's hosted fields (PCI DSS).
Code
JavaScript
const re = /^(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|2(?:2[2-9][1-9]|2[3-9]\d|[3-6]\d\d|7[01]\d|720)\d{12}|3[47]\d{13})$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'(?:4\d{12}(?:\d{3})?|5[1-5]\d{14}|2(?:2[2-9][1-9]|2[3-9]\d|[3-6]\d\d|7[01]\d|720)\d{12}|3[47]\d{13})', value))Try it on your own input
The live tester adds the g and m flags so every line is checked separately.
Questions
Which part identifies the card brand?
The leading digits (the IIN): 4 for Visa, 51–55 and 2221–2720 for Mastercard, 34 or 37 for Amex.
More patterns
Email regexPhone number regexURL regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regex