Validates numbers using the Luhn algorithm (mod 10).

The Luhn algorithm is a checksum formula used to validate identification numbers such as credit card numbers, IMEI numbers, and others.

Supports arbitrary bases (default base 10).

Examples

iex> Luhn.valid?("378282246310005")
true

iex> Luhn.valid?(4111111111111111)
true

iex> Luhn.valid?("abc1239", 16)
true

iex> Luhn.valid?("1234567890")
false

Summary

Functions

Calculates the Luhn checksum for the given number.

Checks whether the given number is valid according to the Luhn algorithm.

Functions

checksum(number, base \\ 10)

@spec checksum(integer() | String.t(), pos_integer()) :: non_neg_integer()

Calculates the Luhn checksum for the given number.

Returns 0 if the number is valid. Accepts strings or integers.

Examples

iex> Luhn.checksum("378282246310005")
0

iex> Luhn.checksum("123456789123456")
8

valid?(number, base \\ 10)

@spec valid?(integer() | String.t(), pos_integer()) :: boolean()

Checks whether the given number is valid according to the Luhn algorithm.

Accepts either a string or integer representation of the number. An optional base parameter can be provided (defaults to 10).

Examples

iex> Luhn.valid?("378282246310005")
true

iex> Luhn.valid?(378282246310005)
true

iex> Luhn.valid?(0xABC1239, 16)
true

iex> Luhn.valid?("123456789123456")
false