Validates a number against the Luhn checksum, or computes the Luhn check digit to append to a number.
Published for review. The Founder is checking every card himself; anything he strikes comes down the same hour.
Try it
Inputs
mode (string, required) one of: validate, compute_check_digit : Whether to validate a full number or compute a check digit for a number missing one.
number (string, required) : Digits only. For validate: the full number including its check digit. For compute_check_digit: the number without its check digit.
Outputs
result: For validate: true or false. For compute_check_digit: the single check digit (0-9).
Steps
The Luhn algorithm (used for card numbers per ISO/IEC 7812-1): starting from the rightmost digit of the full number (the check digit) and moving left, double every second digit; if doubling produces a number greater than 9, subtract 9 from it.
Sum all the digits (doubled ones after the above adjustment, others unchanged).
The number is valid if that sum is a multiple of 10.
To compute a missing check digit: try each digit 0-9 appended to the given number until the resulting full number's Luhn sum is a multiple of 10; that digit is the check digit.
Constants
None.
Sources
ISO/IEC 7812-1 (Luhn checksum for card numbers) (ISO/IEC, 2026-09-30T20:01:00Z) - Standard specifying the Luhn (mod 10) check algorithm for payment card numbers.