A checkout form that accepts any string in the card number box pushes the problem downstream, where it surfaces as a failed payment and a confused customer. A format check at the field catches the common accidents early: a digit lost while copying, a number pasted with its spaces, an expiry date fragment in the wrong box. A regular expression is the usual tool for that check, and a good one, as long as you are clear about what it proves.
This guide builds the pattern piece by piece and tests it in the free Regex Tester on Ovatly, which runs a JavaScript regular expression against your text and lists every match with its position and capture groups. It also states the limit plainly: this is a format check, not a card check.
Contents
- Quick answer
- What a format check actually examines
- The 16-digit pattern, piece by piece
- The 15-digit layout
- How to test the pattern, step by step
- Worked example: numbers that pass and numbers that fail
- Limitations
- Common mistakes
- FAQs
- Conclusion
Quick answer
For the common 16-digit shape, use this anchored pattern: ^\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$. It accepts 1234567890123456, 1234 5678 9012 3456 and 1234-5678-9012-3456, and rejects anything shorter, longer or wrongly grouped. For the 15-digit layout grouped 4-6-5, use ^\d{4}[ -]?\d{6}[ -]?\d{5}$. Paste either pattern into the Regex Tester, typed without slashes, and test it against samples that should pass and should fail. Hold on to the limit from the start: a regex checks format only. It cannot run the Luhn checksum, cannot tell a real issued card from a made-up number with the right shape, and must never be the only check before taking a payment.
What a format check actually examines
A card number, as typed, has three properties a pattern can examine: digit count (most cards carry 16 digits, a common second layout 15), grouping (four groups of four, or a 4-6-5 split on the 15-digit layout), and separators (spaces, dashes, or nothing).
That is the whole of it. The pattern sees characters, not a bank account. It knows nothing about whether the number was ever issued, or whether the digits pass the checksum real card numbers are built to satisfy.
The 16-digit pattern, piece by piece
Start with the digit itself. \d matches one digit, and a quantifier in braces repeats it an exact number of times, so \d{4} is one group of four digits. Four of those, end to end, give the plain 16-digit run: \d{4}\d{4}\d{4}\d{4}.
Real input arrives with separators, so between each pair of groups the pattern allows one optional separator. The class [ -] means one character that is either a space or a dash (inside a class, a dash at the end is literal, not a range), and the ? makes it optional: \d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}.
The last pieces are the anchors. ^ pins the match to the start of the input and $ to the end, giving ^\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$. With anchors, the whole string must be exactly the card shape, nothing before or after it.
The 15-digit layout
The second common layout holds 15 digits grouped 4-6-5. The same construction applies, with the group sizes changed: ^\d{4}[ -]?\d{6}[ -]?\d{5}$. It accepts 1234 567890 12345 and rejects the 4-4-4-3 grouping 1234 5678 9012 345, which has 15 digits but the wrong shape.
Both shapes can be combined in one pattern with an alternation, but two small patterns are easier to read, test and fix. Write one anchored pattern per layout your form accepts.
How to test the pattern, step by step
- Open the Regex Tester.
- Type the pattern in the Pattern field, without slashes:
^\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$. Leave the Flags field empty; withoutgthe tester reports the first match, all a yes-or-no check needs. - Paste a sample that should pass, such as
1234 5678 9012 3456. The match list should show one match covering the whole string, at index 0. - Replace it with numbers that should fail, one at a time, and confirm each reports no match.
- If the tester reports an invalid pattern, read its plain-language error: an unclosed bracket or trailing backslash is the usual cause.
Worked example: numbers that pass and numbers that fail
Run the 16-digit pattern against these invented samples:
| Sample input | Result | Why |
|---|---|---|
1234 5678 9012 3456 | Match | 16 digits, groups of four, spaces |
1234-5678-9012-3456 | Match | Same shape, dashes |
1234567890123456 | Match | Separators are optional |
1234 5678 9012 345 | No match | 15 digits, 4-4-4-3 grouping |
1234 5678 9012 34567 | No match | 17 digits; the end anchor rejects it |
1234 5678 9012 | No match | Only three groups |
Two results deserve a second look. The 17-digit sample fails only because of the anchors, as the paragraph after the table shows. And every passing sample has just one thing in common: correct shape. 1234 5678 9012 3456 is a made-up sequence no card scheme issued, and the pattern accepts it happily, because shape is all it can see.
If you want the groups separately, capture them: ^(\d{4})[ -]?(\d{4})[ -]?(\d{4})[ -]?(\d{4})$. The match list then shows each group alongside the full match, as the tester's own example shows groups ada and example for (\w+)@(\w+)\.com on [email protected]. Named groups such as (?<first>\d{4}) label each group in the match details.
The anchors are what make that 17-digit rejection happen. Drop them, and the unanchored \d{16} run against 12345678901234567 reports a match: the first 16 digits, at index 0. An unanchored pattern asks "does this shape appear anywhere in the text", and it does. Validation asks a stricter question: "is this text, all of it, exactly this shape". The ^ and $ turn the first question into the second, and they catch pasted junk too: a number copied with a leading word fails an anchored pattern.
Limitations
The format check cannot run the Luhn checksum, the arithmetic test real card numbers are constructed to pass, which catches most single-digit typos and transpositions. A number can have a perfect shape and fail Luhn, or pass this pattern while belonging to no card ever issued. Treat the regex as a typing aid, never as evidence that a card is genuine, and never as the only check before taking a payment. Real validation belongs to your payment provider, and wherever possible the raw number should travel to that provider rather than through your own systems.
Two smaller limits: the flexible separator class allows mixed separators in one number, so 1234 5678-9012 3456 passes, a cosmetic flaw most format checks accept. And the tester runs JavaScript's RegExp engine, whose rules differ slightly from PCRE, Python or grep flavours, so retest the pattern in your own stack before shipping it.
Common mistakes
- Skipping the anchors. Without
^and$, longer strings and pasted fragments pass. - Testing only passing samples. A pattern nobody tried to break is a guess. Always run the failing set.
- Believing the check proves the card. It proves the shape. Nothing about issuing or the checksum follows from a match.
- Writing one giant pattern for every layout. Separate anchored patterns per layout are easier to verify and change.
- Testing with real numbers. Real card numbers do not belong in testers, logs or screenshots. Invented samples test the shape just as well.
FAQs
Can a regex check that a card number is real? No. A regex checks the format only: the right number of digits in the right grouping with allowed separators. It cannot run the Luhn checksum, and it cannot tell a real issued card from an invented number that happens to have the right shape.
Why does my pattern accept a 17-digit number?
Because without anchors the pattern only needs to find a valid run somewhere inside the text. An unanchored 16-digit pattern matches the first 16 digits of a 17-digit string. Add ^ at the start and $ at the end so the whole input must fit the shape.
Should the pattern allow spaces and dashes? Only if your form accepts them. People copy card numbers in groups of four separated by spaces, and some type dashes. One controlled separator class between groups covers both, but it also allows mixed separators in a single number, which is a cosmetic flaw most format checks accept.
How do I handle the 15-digit layout? Use a separate pattern with a 4-6-5 grouping: four digits, six digits, five digits, with the same optional separator between groups. A single pattern can offer both shapes as alternatives, but two small patterns are easier to read and to test.
Is a format check enough before taking a payment? No, never. Format validation is a typing aid that catches pasted fragments and missing digits early. Real payment checks, including the Luhn checksum and authorisation, belong to your payment provider, and card numbers should go to the provider rather than through your own code wherever possible.
Conclusion
A good card format pattern is small, anchored and tested against failures as well as passes: exact digit counts, one controlled separator, ^ at the start and $ at the end. Build it in the Regex Tester, prove it on invented samples, and keep its job description honest: it tidies input, it does not validate cards. The building block it leans on hardest is the character class, covered in Regex Character Classes and Ranges Explained with Examples. More guides like this one live in the Developer Tools archive.