Bank card number verification - Luhn algorithm

Bank card number verification - Luhn algorithm

1.1 Introduction to
        Luhn Luhn algorithm/formula, also known as "modulo 10 algorithm", is a simple verification formula, which is often used for identification verification of bank card numbers, IMEI numbers and other ID numbers.
        It should be noted that the purpose of the Luhn algorithm is not to be a cryptographically secure hash function, but to prevent errors caused by accidental operations, such as wrong input.
Luhn Algorithm English Reference: https://en.wikipedia.org/wiki/Luhn_algorithm#cite_note-0
1.2 Check
        Rules The correctness of the check code:
        1. According to the order from right to left, starting from the right side of the string of numbers, including the check code, multiply the even digits by 2, if the result of each multiplication is greater than 9 (such as 8 × 2 = 16), then add the ones and tens digits (eg 1 + 6 = 7) or subtract 9 from this result (eg 16 - 9 = 7).
        2. After the first step, a new string of numbers will be obtained, and the sum of all numbers (including the check code) will be calculated.
        3. Use the sum obtained in the second step to perform the "modulo 10" operation. If the result is 0, it means that the verification passes, otherwise it fails.
1.3 Examples
function bankCheckCodeValidate(str) {
    var sum = 0, evenArr = [], oddArr = [];
    var numArr=str.split("").reverse();
    for(var i=0;i<numArr.length;i++){
        i%2 != 0 ? evenArr.push(numArr[i]*2) : oddArr.push(numArr[i]);
    }
    for(var x=0;x<evenArr.length;x++){
        evenArr[x]>9 ? sum+=(evenArr[x]-9) : sum+=evenArr[x];
    }
    for(var k=0;k<oddArr.length;k++){
        sum+=parseInt(oddArr[k]);
    }
    return (sum%10 == 0);
}

1.4
Advantages and Disadvantages         The Luhn algorithm can detect any single code error and almost all the errors caused by the exchange of adjacent numbers, but it cannot detect the exchange errors of the two digital sequences 09 and 90. It can detect the same two-digit swap errors on a scale of seven out of ten (except for 2 ↔ 55, 33 ↔ 66 and 44 ↔ 77).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484975&siteId=291194637