From time to time, it’s required to generate codes for users that they can use to claim some discounts or bonuses later. Instead of inventing something yourself, you can use the existing library called coupon-code:

npm install coupon-code --save

The interface of the module is simple. To generate a code, call generate:

To validate a code, use validate method. This method does not only validate the entered code, it deals with the input errors as well. Before validating, the method uppercases the code and then replaces letters that are similar to numbers with numbers: O -> 0, Z -> 2, S -> 5 and I -> 1. So if user confuses some letters/numbers, his voucher will still be validated successfully.

The validate method returns an empty string if the input is invalid and the canonical code if the input is valid even if there are input errors. Generation algorithm ensures that all versions with typos result in the same canonical code.

It’s important to provide the correct of the code (i.e. parts and partLen) as the library will not derive them.

Practical Usage

Uniqueness is not ensured by the algorithm. Therefore your application has to make sure that the generated code is unique. For example, if the check is possible in a synchronous manner: