-
-
Save gbaldera/5722966 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint maxerr:1000 */ | |
var my = {tools:{}}; | |
//Import our module into our project | |
my.tools.cardHelper = require('credit_card_helper'); | |
//Our test credit card number that we got from http://www.getcreditcardnumbers.com/ | |
var testCreditCardNumber ="49713268648235453"; | |
//Call our verify method to check if our credit card number is in a correct format | |
var ccCheck = my.tools.cardHelper.verifyCardWithLuhn(testCreditCardNumber); | |
//alert the result back to the user | |
alert(ccCheck); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jslint maxerr:1000 */ | |
exports.verifyCardWithLuhn=function(cardNumber){ | |
//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) { | |
mod10=0; | |
} | |
//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