validation

Credit Card Number (Generic) Regex Pattern

Validates the FORMAT of a 16-digit credit card number (Visa, Mastercard, Discover). Accepts optional spaces or dashes between groups. Does NOT check the Luhn checksum — for real payment validation, always use a Luhn check server-side too.

/^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/

What each part matches

^\d{4} — first 4 digits
[\s-]? — optional space or dash
\d{4}[\s-]?\d{4}[\s-]?\d{4}$ — three more groups of 4 digits

✓ These match

  • 4111 1111 1111 1111
  • 4111-1111-1111-1111
  • 4111111111111111

✗ These don't

  • 4111 1111 1111
  • 41111 11111 11111
  • 4111-1111-1111-11111

Use in your code

JavaScript

const re = /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/;
re.test(input); // → true or false

Python

import re
re.fullmatch(r"^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$", input)

PHP (PCRE)

preg_match('/^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/', $input);

Go

re := regexp.MustCompile(`^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$`)
re.MatchString(input)

FAQ

Does this credit card number (generic) regex work in JavaScript?
Yes. Every pattern in the Utilko regex library is tested to work in JavaScript RegExp, PCRE (PHP, Nginx), and Python `re`. Where flavor matters (lookbehind, named groups), the pattern page flags it.
How do I use this pattern?
Copy the pattern from the code block above. In JavaScript: new RegExp('^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$') or literal /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/. Or click "Try in regex tester" to open it pre-loaded in Utilko's browser-based regex tester.
Should I use this for security-critical validation?
Client-side regex is fine for UX (immediate feedback on a form). For anything security-critical — payments, auth, data integrity — always re-validate server-side using the same pattern PLUS domain-specific checks (Luhn checksum for cards, actual email delivery test, DNS resolution for domains).

Related regex patterns

← All regex patterns · Regex tester · Regex cheat sheet