@Evanion/Luhn
A Luhn mod-N library.
This library will generate and validate checksum characters based on the Luhn mod-N (or mod 10) algorithm.
import { Luhn } from '@Evanion/luhn';
import { generateRandom } from 'some_library';
const createToken = () => {
const randomString = generateRandom();
const { checksum } = Luhn.generate(randomString);
return `${randomString}-${checksum}`;
};
installation
npm install @evanion/luhn
yarn add @evanion/luhn
Breaking changes
version 1.x.x contains a faulty calculation of how checksums are calculated, please take in to account when upgrading
What is the Luhn and Luhn mod-N Algorithms?
The Luhn algorithm is a simple checksum formula used to validate identification numbers such as credit card numbers, IMEI numbers, social security/insurance numbers, and National identification numbers in some countries.
The mod-N algorithm is an extension to the regular Luhn algorithm, that adds support for alphanumerical strings.
Why should you use the Luhn algorithm
The luhn algorithm allows you to quickly validate an input, without having to look it up in a database. It's useful when you want to improve the user experience in cases where a user needs to input a string of characters. Like a license key, gift card number, or similar.
Generate a checksum
Generating a checksum is simple
const checked = Luhn.generate('foo'); // -> {phrase: 'foo', checksum: '5'}
Case-insensitive
The library defaults to being case insensitive.
const checked = Luhn.generate('FoO'); // -> {phrase: 'foo', checksum: '5'}
Case-sensitive
If you need to be case sensitive, you can extend the Luhn class and override the sensitive
property.
class SensitiveLuhn extends Luhn {
static readonly sensitive = true;
}
or, you can pass the sensitive
property to the generate method.
Luhn.generate('FoO', true); // -> {phrase: 'FoO', checksum: '5'}
Luhn.validate('FoO5', true); // -> {phrase: 'FoO5', isValid: true}
Filtering
The generate method will filter out any characters not in the dictionary
Luhn.generate('foo-baz'); // -> {phrase: 'foobaz', checksum: 'p'}
Luhn.generate('fooö-baz'); // -> {phrase: 'foobaz', checksum: 'p'}
Validate a string
Validating a string is also simple
Luhn.validate('foo5'); // -> {phrase: 'foo5', isValid: true}
Luhn.validate('FoOö5'); // -> {phrase: 'foo5', isValid: true}
Luhn.validate('FoO-ö5'); // -> {phrase: 'foo5', isValid: true}
Luhn.validate('bar5'); // -> {phrase: 'bar5', isValid: false}
Dictionary
The default dictionary contains a-z and 0-9. If you need to support other dictionaries, you can override the default one.
class MyLuhn extends Luhn {
static dictionary =
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÅåÄäÖö';
}