luhn – simple credit card validation for JavaScript and Node.js

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

Using with JavaScript

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.

UPDATE – 09 Aug. 2012: the module has been updated to utilize NPM more to make client-side installation easier than manually copying the script from node_modules or referencing directly from node_modules. Typing in the following command will prompt you for a client-side installation directory and then will automatically copy the script to your JavaScript source directory.

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.

<script type="text/javascript" src="path/to/luhn-min.js"></script>
<script type="text/javascript">
var luhn = window.luhn;
var is_valid = luhn.validate("1234567890123456"); // returns false


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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close