Skip to content

Instantly share code, notes, and snippets.

Last active December 10, 2015 03:28
What would you like to do?
Luhn Credit Card Validation algorithm implemented as CommonJS module
/*jslint maxerr:1000 */
var my = {tools:{}};
//Import our module into our project = require('credit_card_helper');
//Our test credit card number that we got from
var testCreditCardNumber ="49713268648235453";
//Call our verify method to check if our credit card number is in a correct format
var ccCheck =;
//alert the result back to the user
/*jslint maxerr:1000 */
//Remove spaces
cardNumber = cardNumber.replace(/[^\d]/g, "");
//Grab our length for use later
var cardLength = cardNumber.length;
//If no length return invalid
if (cardLength === 0){
return false;
//Get last digit
var lastDigit = parseInt(cardNumber.substring((cardLength-1),cardLength),10);
//Build string with all credit card digits minus the last one
var cardNumberMinusLastDigit = cardNumber.substring(0,(cardLength-1));
//Build up our variables needed for our calculation
var sum = 0, luhnLength = cardNumberMinusLastDigit.length, luhnKey = [0,1,2,3,4,-4,-3,-2,-1,0];
//Step 1 of our hash add the numbers together
for (i=0; i<luhnLength; i++ ) {
sum += parseInt(cardNumberMinusLastDigit.substring(i,i+1),10);
//Step 2 of our has, we now add in our key values
for (i=luhnLength-1; i>=0; i-=2 ) {
sum += luhnKey[parseInt(cardNumberMinusLastDigit.substring(i,i+1),10)]
//Adjust our sum as neeed
var mod10 = sum % 10;
mod10 = 10 - mod10;
if (mod10===10) {
//Our hash should now mast the last digit of our number
return (mod10===lastDigit);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment