Skip to content

Instantly share code, notes, and snippets.

@ryanhamley
Created May 26, 2015 21:06
Show Gist options
  • Save ryanhamley/79f4970c686cc4630465 to your computer and use it in GitHub Desktop.
Save ryanhamley/79f4970c686cc4630465 to your computer and use it in GitHub Desktop.
Javascript implementation of the Luhn algorithm to verify credit card numbers
/**
* [verifyCardNumber implements the Luhn algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm), which is a checksum algorithm to determine card validity. This implementation was developed by BrainJar (http://www.brainjar.com/js/validation/default2.asp)]
* @param {[string]} _num [the credit card number in string format]
* @return {Boolean} [true if valid, else false]
*/
function verifyCardNumber (_num) {
var i, sum, digit, reverse, modified;
// First, reverse the string and remove any non-numeric characters.
reverse = '';
for (i = 0; i < _num.length; i++) {
digit = parseInt(_num.charAt(i), 10);
if (digit >= 0 && digit <= 9) {
reverse = digit + reverse;
}
}
// Check for a bad string.
if (reverse.length <= 1) {
return false;
}
// Now run through each single digit to create a new string. Even digits are multiplied by two, odd digits are left alone.
modified = '';
for (i = 0; i < reverse.length; i++) {
digit = parseInt(reverse.charAt(i), 10);
if (i % 2 !== 0) {
digit *= 2;
}
modified = modified + digit;
}
// Finally, add up all the single digits in this string.
sum = 0;
for (i = 0; i < modified.length; i++) {
digit = parseInt(modified.charAt(i), 10);
sum = sum + digit;
}
// If the resulting sum is an even multiple of ten (but not zero), the card number is good.
if (sum !== 0 && sum % 10 === 0) {
return true;
} else {
return false;
}
}
@Youngreen
Copy link

Hello am trying to create a c++ programme that allows you to enter the meter number and generates for you the token number 19 digits please help am stuck.Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment