Script Valley
Regex: Actually Useful Patterns
Real-World Validation PatternsLesson 5.4

Credit card number regex validation and formatting

card number structure, Luhn algorithm role, format validation vs Luhn check, card type detection, grouping pattern, security note

Format Validation vs Real Validity

Credit card format

Regex validates format and card type prefix. It cannot detect invalid card numbers — that requires the Luhn algorithm. Always run both checks.

const cardRe = /^\d{4}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}$/;

const cardType = (n) => {
  const s = n.replace(/\D/g, '');
  if (/^4/.test(s))           return 'Visa';
  if (/^5[1-5]/.test(s))      return 'Mastercard';
  if (/^3[47]/.test(s))       return 'Amex';
  return 'Unknown';
};

Security Note

Never log, store, or transmit raw card numbers.

Up next

Building a reusable regex validation library in JavaScript

Sign in to track progress