Luhn Checksum Validation for Card Numbers

Validate payment card numbers with the Luhn algorithm, tolerate spaces and hyphens, and compute the missing check digit.

JavascriptForm Validation

Code

javascriptsnippet
45 lines
export function isValidCardNumber(input) {
  const digits = normalize(input);
  if (digits.length < 12 || digits.length > 19) return false;
  return luhnSum(digits) % 10 === 0;
}

export function cardCheckDigit(partial) {
  const digits = normalize(partial);
  if (digits.length < 11 || digits.length > 18) {
    throw new RangeError("partial number must contain 11 to 18 digits");
  }
  const remainder = luhnSum(`${digits}0`) % 10;
  return String((10 - remainder) % 10);
}

function normalize(input) {
  if (typeof input !== "string" && typeof input !== "number") {
    throw new TypeError("card number must be a string or number");
  }
  const value = String(input).replace(/[\s-]/g, "");
  if (!/^\d*$/.test(value)) {
    throw new Error("card number may only contain digits, spaces and hyphens");
  }
  return value;
}

function luhnSum(digits) {
  let sum = 0;
  let double = false;
  for (let index = digits.length - 1; index >= 0; index -= 1) {
    let value = Number(digits[index]);
    if (double) {
      value *= 2;
      if (value > 9) value -= 9;
    }
    sum += value;
    double = !double;
  }
  return sum;
}

const sample = "4242 4242 4242 4242";
console.log(isValidCardNumber(sample));
console.log(isValidCardNumber("4242424242424241"));
console.log(cardCheckDigit("424242424242424"));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

true
false
2

What the code does

Count the functions isValidCardNumber, cardCheckDigit, normalize and luhnSum as the entire surface area of Luhn Checksum Validation for Card Numbers.

One loop does the cycling here: for (let index = digits.length - 1; index >= 0; index -= 1). When the guard condition holds, RangeError, TypeError and Error is thrown rather than a bogus value returned.

Watch out for

  • The guard digits.length < 12 || digits.length > 19 short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is export function isValidCardNumber(input)

Import isValidCardNumber from the file and call it — the rest of the code is implementation detail.

Statements that matter

throw new Error("card number may only contain digits, spaces and hyphens");
throw new RangeError("partial number must contain 11 to 18 digits");
throw new TypeError("card number must be a string or number");

Interactive Tools for This Topic

FAQ

Does the code validate its input?
The code throws `RangeError`, `TypeError` and `Error` — the guard `digits.length < 12 || digits.length > 19` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `isValidCardNumber`, `cardCheckDigit`, `normalize` at load time.