If you’ve worked on websites for any amount of time, there is a decent chance that you’ve encountered the need to validate credit card numbers at some point. While there are a lot of compliance and security guidelines for working with credit card numbers, these don’t reduce the need for ensuring the user entered a valid credit card number into the form. Some places will validate just length and ensure only numeric digits were provided; however, did you know there’s an algorithm that most credit cards are based on?
luhn (npm, github) provides this algorithm (known as the luhn or mod10 algorithm – wikipedia) for validating credit card numbers into a simple script that can be reused in both your browser and node.js applications.
Installing luhn is simple thanks to NPM. To install it, simply type the following command.
npm install luhn
Using with Node.js
Once the package is installed using NPM, using the luhn is as simple as importing in the module into your code.
var luhn = require("luhn").luhn; var is_valid = luhn.validate("1234567890123456"); // returns false
One goal I had when writing luhn was to ensure that it can be used both client and server side. Being able to use it in both places ensure that you can write your validation code once and reuse it wherever.
npm run-script luhn client-install
To use the luhn in object from a client’s browser, you simply have to reference the script using a typical
<script> tag and then use pretty much the same as above.
The luhn module is still in its early stages and I’m always looking for feedback. If you have any suggestions or find any bugs, please submit them to the issue tracker over on github and I’ll see what I can do to get them updated. In addition, if you are looking for information on test credit card numbers to use, please refer to this link from PayPal.