DevTools Logo
All posts

Credit Card Validation and the Luhn Algorithm Explained

August 15, 2026 · DevTools

security
credit-card
luhn-algorithm
ecommerce

Credit Card Validation and the Luhn Algorithm Explained

Payment gateways and checkout forms validate card numbers client-side before sending requests to payment processors like Stripe or PayPal. This prevents obvious typos without transmitting sensitive data.

Test and validate card numbers:

How the Luhn Algorithm (MOD 10) Works

  1. Starting from the rightmost digit (excluding the check digit), double the value of every second digit.
  2. If doubling results in a number greater than 9, subtract 9 (or sum its digits: $16 \to 1+6 = 7$).
  3. Sum all the digits.
  4. If the total modulo 10 equals 0, the number is valid.
function isValidLuhn(cardNumber) {
  const digits = cardNumber.replace(/\D/g, "");
  let sum = 0;
  let isEven = false;

  for (let i = digits.length - 1; i >= 0; i--) {
    let digit = parseInt(digits.charAt(i), 10);
    if (isEven) {
      digit *= 2;
      if (digit > 9) digit -= 9;
    }
    sum += digit;
    isEven = !isEven;
  }
  return sum % 10 === 0;
}

Generate dummy card numbers for test suites with the Credit Card Generator.

Tools mentioned in this post