How the Luhn Algorithm Validates Credit Card Numbers (With Code)

A worked example of the Luhn mod-10 check, how card prefixes and lengths identify networks, reusable JavaScript, and why a valid number is not a real card.

Updated September 29, 2026 6 min read

Use the free Credit Card ValidatorCheck a card number’s Luhn checksum, length and network — no bank contact

When someone types a card number into a checkout form, the first thing a well-built form does is not contact a bank. It runs a quick arithmetic check on the digits, right in the browser, to catch typos before the payment request is even sent. That check is the Luhn algorithm, and it is also why a mistyped digit is often rejected instantly.

This guide walks through the Luhn calculation step by step, explains how the leading digits reveal the card network and expected length, gives you tested JavaScript for your own forms, and is clear about the limits: passing these checks says nothing about whether a card exists or can be charged.

The anatomy of a card number

A payment card number (formally a primary account number, or PAN) has three parts:

Part Digits Meaning
Issuer identification number (IIN, often called BIN) First 6 or 8 Identifies the network and issuing institution
Account identifier Middle digits Assigned by the issuer
Check digit Last 1 Calculated with the Luhn formula

The very first digit is the major industry identifier: 4 is used by Visa, 5 and 2 by Mastercard, 3 by American Express, Diners Club and JCB, and 6 by Discover, UnionPay and others. Typical prefixes and lengths are:

Network Common prefixes Length Security code
Visa 4 13, 16 or 19 3 digits
Mastercard 51–55, 2221–2720 16 3 digits
American Express 34, 37 15 4 digits
Discover 6011, 644–649, 65 16–19 3 digits

Prefix ranges are occasionally extended by the networks, so treat any hard-coded list as something to review over time.

The Luhn check, step by step

The Luhn algorithm (also called mod 10), created at IBM in the 1950s, works on any string of digits:

  1. Starting from the rightmost digit (the check digit) and moving left, double every second digit.
  2. If doubling gives a number above 9, subtract 9 (the same as adding its two digits).
  3. Add up all the digits, doubled and undoubled.
  4. If the total is a multiple of 10, the number passes.

Here is the classic textbook example, 79927398713:

Digit (right to left) 3 1 7 8 9 3 7 2 9 9 7
Doubled? no yes no yes no yes no yes no yes no
Value used 3 2 7 7 9 6 7 4 9 9 7

The sum is 70, which ends in zero, so the number is valid.

What Luhn catches and misses

Luhn detects every single-digit error and almost every swap of two adjacent digits. It misses the swap of 09 and 90, and some twin errors such as 22 becoming 55. It is a typo filter, not a security feature: anyone can compute a valid check digit for any prefix.

Check a number with our tool

The Credit Card Validator runs all checks in the page. Nothing is sent, logged or stored.

  1. Type or paste the number into Card number. Spaces and dashes are ignored.
  2. Read the badge: Valid structure or Invalid, together with the detected network.
  3. Look at the three checks: the Luhn checksum, the issuer prefix and the length for that network. If the checksum fails, the tool shows which final digit would have passed, which usually points to the typo.
  4. Review the details table for the major industry identifier, the IIN/BIN, the check digit and the expected security code length.
  5. For testing, click any of the Official test numbers (click to try), which come from Stripe and Braintree's public sandbox documentation.

Implement it yourself in JavaScript

This function strips spaces and dashes, rejects anything that is not 12 to 19 digits, and applies the Luhn rule. A helper finds the check digit for a partial number, which is handy when generating fixtures for tests.

function luhnValid(input) {
  const digits = String(input).replace(/[\s-]/g, "");
  if (!/^\d{12,19}$/.test(digits)) return false;
  let sum = 0;
  let double = false; // the rightmost digit (check digit) is not doubled
  for (let i = digits.length - 1; i >= 0; i--) {
    let d = Number(digits[i]);
    if (double) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
    double = !double;
  }
  return sum % 10 === 0;
}

// Compute the check digit for a number without one
function luhnCheckDigit(partial) {
  for (let c = 0; c <= 9; c++) if (luhnValid(partial + c)) return c;
}

console.log(luhnValid("4242 4242 4242 4242")); // true  (Stripe test Visa)
console.log(luhnValid("4242 4242 4242 4241")); // false (last digit changed)
console.log(luhnValid("5555 5555 5555 4444")); // true  (Stripe test Mastercard)
console.log(luhnCheckDigit("424242424242424"));  // 2

In a real checkout, combine this with a prefix and length check, and treat the result as a hint to the user ("please check the number"), not as a gate. Let the payment provider make the final decision.

Better still: let the provider's fields do it

If you use a payment provider's hosted fields or embedded checkout, the provider validates the number and the card data never touches your servers. That also keeps most of your systems out of the scope of card data security requirements. Custom validation is mostly useful for back-office tools, data cleaning and teaching.

Testing payments safely

Use only the official test numbers published by your payment provider, in its test or sandbox mode. They trigger predictable outcomes (success, decline, authentication required) and never move real money. Do not invent numbers that happen to pass Luhn, and never copy a real customer's card into a test environment, bug report, spreadsheet or chat. For other kinds of test data, such as unique order references, the UUID Generator is a safer source of realistic-looking identifiers.

Pitfalls and edge cases

A valid number is not a real card

This is the key limitation. A number that passes Luhn, prefix and length checks may never have been issued, may be cancelled or expired, or may have no funds. Only an authorisation through a payment network can tell you that.

Formatting in the input

Customers paste numbers with spaces, dashes or non-breaking spaces. Strip separators before validating, but reject letters rather than silently removing them.

Networks without a Luhn digit

Some older UnionPay cards were issued without a valid Luhn check digit, so a failure there is not always a typo. Be cautious about hard-rejecting them.

Other identifiers use other checks

Bank account numbers use different schemes. International bank account numbers, for example, use a mod-97 check, which our IBAN Validator implements. Never apply the card rules to them.

Don't store numbers for later validation

If you are cleaning old data, do it where the data already lives and discard full numbers you do not need. Storing card numbers without strict controls creates serious security and compliance risk; if you only need to match records, keep the last four digits or a keyed hash from a tool like the HMAC Generator rather than the full number.

Frequently asked questions

Does passing the Luhn check mean the card is real?

No. It only means the digits are consistent with the formula. Anyone can create a Luhn-valid number, and only the issuer can confirm that an account exists and is active.

Can I use generated or test numbers to buy things?

No. Official test numbers work only in payment providers' sandbox modes, and made-up numbers are declined by real payment systems. Using invented card numbers for real purchases is fraud.

Is it safe to type my real card number into a validator?

A validator that runs locally sends nothing, but as a rule only enter real card details on checkout pages you trust. For development, use official test numbers instead.

Why is the IIN now eight digits?

The industry has been moving from 6-digit to 8-digit issuer identification numbers to allow more issuers. Code that assumes exactly six digits may need updating.

Is the Luhn algorithm used anywhere else?

Yes. It is used for IMEI numbers on mobile phones and several national identification numbers, among others.

Try it now: Credit Card Validator

Loading tool…