LUHN算法,主要用来计算信用卡等证件号码的合法性。
next section from:http://en.wikipedia.org/wiki/Luhn_algorithm
The Luhn algorithm or Luhn formula, also known as the " 10" or "mod 10" , is a simple formula used to validate a variety of identification numbers, such as , , in US and . It was created by scientist and described in , filed on January 6, 1954, and granted on August 23, 1960.
The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test:
- Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
- Sum the digits of the products together with the undoubled digits from the original number.
- If the total ends in 0 (put another way, if the total modulo 10 is equal to 0), then the number is valid according to the Luhn formula; else it is not valid.
As an illustration, if the account number is 49927398716, it will be validated as follows:
- Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
- Sum all the individual digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70
- Take the sum modulo 10: 70 mod 10 = 0; the account number is valid.
翻译过来就是:
1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。 2、将偶数位数字相加,但是这里有个麻烦。必须先将数字乘以2,如果结果是两位数,将两个位上数字相加。然后将这些结果加入总和中。 3、将奇数位总和加上偶数位总和,如果信用卡号码是合法的,结果应该可以被10整除。现已Master Card为例:
//from:professional JavaScript for web developers
<script>
function isValidMasterCard(sText){ var reMasterCard=/^(5[1-5]\d{2})[\s\-]?(\d{4})[\s\-]?(\d{4})[\s\-](\d{4})$/; if(reMasterCard.test(sText)){ var sCardNum=RegExp.$1+RegExp.$2+RegExp.$3+RegExp.$4; alert(sCardNum); //Luhn algorithm here return luhnCheckSum(sCardNum); }else{ return } } function luhnCheckSum(sCardNum){ var iOddSum=0; var iEvenSum=0; var bIsOdd=true; for(var i=sCardNum.length-1;i>=0;i--){ //alert("length="+sCardNum.length); //alert("sCardNum.char("+i+")="+sCardNum.charAt(i)); var iNum=parseInt(sCardNum.charAt(i)); if(bIsOdd){ //反向奇数求和 iOddSum+=iNum; }else{ //偶数 if(iNum>9){ iNum=eval(iNum.toString().split("").join("+")); } iEvenSum+=iNum; } bIsOdd=!bIsOdd; } return ((iEvenSum+iOddSum)%10==0); } alert(isValidMasterCard("5432 1234 5678 9012")); alert(isValidMasterCard("5432-1234-5678-9012")); </script>