# Regex for Credit Card Numbers

> Credit card regex that checks 13–19 digits with optional spaces or hyphens, plus Visa and Mastercard prefixes, and why you still need the Luhn check.

```
/^(?:\d[ -]?){12,18}\d$/
```

Card numbers are 13 to 19 digits, usually written in groups separated by spaces or hyphens. This pattern accepts that shape and nothing else. A regex can't tell whether a number is valid — follow it with the Luhn checksum — and avoid handling raw card numbers on your own servers at all.

## Token by token

| Token | Meaning |
|---|---|
| `^` | start of string |
| `(?:\d[ -]?){12,18}` | 12 to 18 digits, each optionally followed by one space or hyphen |
| `\d` | a final digit, so there's no trailing separator |
| `$` | end of string |

## Examples

- ✓ matches: `4111 1111 1111 1111`
- ✓ matches: `5500-0000-0000-0004`
- ✓ matches: `340000000000009`
- ✗ does not match: `4111 1111 1111`
- ✗ does not match: `4111  1111 1111 1111`
- ✗ does not match: `4111-1111-1111-111a`

## Variations

- `^4\d{12}(?:\d{3}){0,2}$` — Visa: starts with 4; 13, 16 or 19 digits (separators removed)
- `^(?:5[1-5]\d{2}|2(?:22[1-9]|2[3-9]\d|[3-6]\d{2}|7[01]\d|720))\d{12}$` — Mastercard: 51–55 or 2221–2720, 16 digits

## Language notes

- Remove separators before checking brand prefixes or running Luhn — in JavaScript, value.replace(/[ -]/g, "").

## FAQ

### What is the Luhn check?

A checksum built into every card number: from the right, double every second digit, subtract 9 from any result over 9, and add everything up. Valid numbers total a multiple of 10. It catches typos, not fraud.

### Should my server see card numbers at all?

Avoid it. Use your payment provider's hosted fields (such as Stripe Elements), so raw numbers go straight to the provider and most PCI DSS requirements stay off your plate.

## Related patterns

- [Regex for Numbers Only (Digits)](https://www.devkult.com/regex/digits-only.md)
- [Regex for Phone Number Validation](https://www.devkult.com/regex/phone-number.md)
- [Regex for US ZIP Codes](https://www.devkult.com/regex/us-zip-code.md)

Open the interactive page: https://www.devkult.com/regex/credit-card