ChildOfCode


Code, Maker, Robotic, Open Source. Knowledge Bases


Java Script - Luhn Algorithm

The Luhn Algorithm in JavaScript

Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers. By Wikipedia

/* Luhn Algorithm JavaScript by childofcode.com */

function LuhnAlgorithm(num){

    var inputNum = num.toString();
    var sum = 0;
    var doubleUp = false;

    /* from the right to left, double every other digit starting with the second to last digit.*/
    for (var i = inputNum.length - 1; i >= 0; i--)
    {
        var curDigit = parseInt(inputNum.charAt(i));

        /* double every other digit starting with the second to last digit */
        if(doubleUp)
        {
            /* doubled number is greater than 9 than subtracted 9 */
            if((curDigit*2) > 9)
            {
              sum +=( curDigit*2)-9;
            }
            else
            {
              sum += curDigit*2;
            }
        }
        else
        {
          sum += curDigit;
        }
        var doubleUp =!doubleUp
    }

  /* sum and divide it by 10. If the remainder equals zero, the original credit card number is valid.  */
  return (sum % 10) == 0  ? true : false;

};

Algorithm Description:

Example 1: 8675309

Example 2: 912030

Note Normally Credit card number should have 16 digit

1.If there are an even number of digits, double every other digit starting with the first, and if there are an odd number of digits, double every other digit starting with the second. Another way to think about it is, from the right to left, double every other digit starting with the second to last digit. (In My code is using the right to left method)

Example 1: 8 (6+6) 7 (5+5) 3 (0+0) 9 >> 8 12 7 10 3 0 9

Example 2: (9+9) 1 (2+2) 0 (3+3) 0 >> 18 1 4 0 6 0

2.If a resulting doubled number is greater than 9, replace it with either the sum of it's own digits, or 9 subtracted from it.(In My code is subtracted 9 method)

Example 1: 8 (12-9) 7 (10-9) 3 0 9 >> 8 3 7 1 3 0 9

Example 2: (18-9) 1 4 0 6 0 >> 9 1 4 0 6 0

3.Sum all of the final digits

Example 1: 8+3+7+1+3+0+9 >> 31

Example 2: 9+1+4+0+6+0 >> 20

4.Finally, take that sum and divide it by 10. If the remainder equals zero, the original credit card number is valid. (Modular Operator % returns the division remainder)

Example 1: 31%10 > 1 >> not valid

Example 2: 20%10 > 0 >> Valid