One input contract, four executable implementations

These helpers calculate the same checksum and are tested against one JSON fixture. The JavaScript implementation is also imported by the site’s interactive tools. The Python, PHP and Ruby examples are displayed directly from their downloadable source files, so the code shown here is the code that the verification command runs.

For the calculation itself, start with the worked Luhn example. This page focuses on reproducing results and catching differences between languages.

Download and run

Extract the complete validation bundle into one directory. It contains the shared vectors, the JavaScript module and test runners, the three other implementations, and the profile cases used by the site tools.

LanguageRun from the extracted directoryRuntime requirement
JavaScriptnode --test luhn.test.mjsNode.js 22 or later
Pythonpython3 luhn.pyPython 3.8 or later
PHPphp luhn.phpPHP 7.3 or later
Rubyruby luhn.rbRuby 2.4 or later

Each language runs the same 31 fixed expectations. The JavaScript runner additionally checks single-digit mutations and check-digit round trips. No dependency installation, network service or real payment data is involved.

Make invalid input stay invalid

The helpers accept strings of ASCII digits with ordinary spaces, nonbreaking spaces or hyphens. They reject letters, tabs, newlines and other numeral systems. They also reject numeric API values, which may already have lost precision before reaching the helper.

The checksum helper requires at least two digits. It rejects 0, while 00 passes the arithmetic check; neither is a complete card number. A check-digit payload has a different contract: a nonempty ASCII digit string with no separators. An invalid payload returns null/None/nil, rather than an invented digit.

The fixture includes 4111x111111111111 because deleting the x would manufacture a passing value. Separators are an allowlist, not a blanket instruction to remove everything except digits.

JavaScript

Save the full module when using these helpers together; the checksum code calls the normalization function shown first. Exports are ES modules and the test runner imports them without copying the implementation into a second file.

export function normalizeInput(input) {
  if (typeof input !== 'string') return { status: 'type', digits: '' };
  // Accept only ASCII digits, ordinary/NBSP spaces and ASCII hyphens.
  if (/[^0-9 \u00a0-]/u.test(input)) return { status: 'characters', digits: '' };
  const digits = input.replace(/[ \u00a0-]/g, '');
  return { status: digits ? 'ok' : 'empty', digits };
}
function luhnSum(digits, double) {
  let sum = 0;
  for (let i = digits.length - 1; i >= 0; i -= 1, double = !double) {
    let digit = digits.charCodeAt(i) - 48;
    if (double) digit = digit * 2 > 9 ? digit * 2 - 9 : digit * 2;
    sum += digit;
  }
  return sum;
}

export function luhnValid(input) {
  const { status, digits } = normalizeInput(input);
  // This helper's input contract requires at least two digits, not a PAN length.
  return status === 'ok' && digits.length >= 2 && luhnSum(digits, false) % 10 === 0;
}

export function luhnCheckDigit(payload) {
  if (typeof payload !== 'string' || !payload || /[^0-9]/.test(payload)) return null;
  return String((10 - luhnSum(payload, true) % 10) % 10);
}

Python

Explicit ASCII ranges avoid treating a broader Unicode digit category as interchangeable with the input contract. The runner checks results with exceptions rather than relying on assertions that can be disabled by an optimized interpreter invocation.

def normalize_input(value):
    if not isinstance(value, str) or re.search(r'[^0-9 \u00a0-]', value):
        return None
    return re.sub(r'[ \u00a0-]', '', value)


def luhn_sum(digits, double):
    total = 0
    for char in reversed(digits):
        digit = ord(char) - 48
        if double:
            digit = digit * 2 - 9 if digit > 4 else digit * 2
        total += digit
        double = not double
    return total


def luhn_valid(value):
    digits = normalize_input(value)
    return digits is not None and len(digits) >= 2 and luhn_sum(digits, False) % 10 == 0


def luhn_check_digit(payload):
    if not isinstance(payload, str) or not re.fullmatch(r'[0-9]+', payload):
        return None
    return str((10 - luhn_sum(payload, True) % 10) % 10)

PHP

The functions check types before processing input. The runner uses strict result comparisons and throws on a mismatch, independently of PHP’s assertion settings.

function normalize_input($value): ?string {
    if (!is_string($value) || preg_match('/[^0-9 \x{00a0}-]/u', $value) !== 0) return null;
    return preg_replace('/[ \x{00a0}-]/u', '', $value);
}

function luhn_sum(string $digits, bool $double): int {
    $sum = 0;
    for ($i = strlen($digits) - 1; $i >= 0; $i--, $double = !$double) {
        $digit = ord($digits[$i]) - 48;
        if ($double) $digit = $digit > 4 ? $digit * 2 - 9 : $digit * 2;
        $sum += $digit;
    }
    return $sum;
}

function luhn_valid($value): bool {
    $digits = normalize_input($value);
    return $digits !== null && strlen($digits) >= 2 && luhn_sum($digits, false) % 10 === 0;
}

function luhn_check_digit($payload): ?string {
    if (!is_string($payload) || preg_match('/\A[0-9]+\z/', $payload) !== 1) return null;
    return (string) ((10 - luhn_sum($payload, true) % 10) % 10);
}

Ruby

The anchored payload expression uses the beginning and end of the whole string, so a trailing newline cannot become an accepted payload. The same newline rejection appears in the shared vectors for all four languages.

def normalize_input(value)
  return nil unless value.is_a?(String) && !value.match?(/[^0-9 \u00a0-]/)
  value.gsub(/[ \u00a0-]/, '')
end

def luhn_sum(digits, double)
  sum = 0
  digits.reverse.each_byte do |byte|
    digit = byte - 48
    digit = digit > 4 ? digit * 2 - 9 : digit * 2 if double
    sum += digit
    double = !double
  end
  sum
end

def luhn_valid(value)
  digits = normalize_input(value)
  !digits.nil? && digits.length >= 2 && luhn_sum(digits, false) % 10 == 0
end

def luhn_check_digit(payload)
  return nil unless payload.is_a?(String) && payload.match?(/\A[0-9]+\z/)
  ((10 - luhn_sum(payload, true) % 10) % 10).to_s
end

Connect checksum tests to card-format tests

Run node --test card-validation.test.mjs from the same bundle for prefix and length checks. It calls the same inspection function as the number validator. The brand-detection guide explains pending candidates; the length reference states which profiles are covered. Neither result should be inferred from a checksum alone.

How these examples are verified

The site’s full check command runs the Node suites plus the Python, PHP and Ruby runners. It also verifies the built pages’ code excerpts and the ZIP’s contents against the source files. A failed vector, missing runtime or stale download fails the audit.

This revision was exercised with Node.js 25.2.1, CPython 3.11.2, PHP 8.5.1 and Ruby 2.6.10. Those are the executed versions, not a claim that every supported version was tested. The checks prove the stated fixture contract; they do not establish payment acceptance.

Frequently Asked Questions

Which files do I need to run the examples?
The ZIP includes all modules, runners, profiles and JSON fixtures. Extract it into one directory, then run the command for your installed language. No package installation or API credentials are needed.
Do all four languages accept the same input?
Yes. The shared vectors require string input, accept ordinary spaces, nonbreaking spaces and hyphens around ASCII digits, and reject other characters. Check-digit payloads must be nonempty ASCII digit strings without separators.
Does a passing checksum helper validate a card number?
No. It enforces a minimum of two digits and computes the checksum, without selecting a card brand or applying its length set. The tools add those checks through a separate shared profile.
Are missing runtimes silently skipped in the site checks?
No. The validation audit fails if Python, PHP or Ruby is unavailable, or if their vectors fail. Node runs the shared JavaScript suite through the existing example checks.