js 銀行卡號校驗
示例:luhnCheck(62155937000139567)
function luhnCheck(bankno) {
var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位(與luhn進行比較)
var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
var newArr = new Array();
for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存進數組
newArr.push(first15Num.substr(i, 1));
}
var arrJiShu = new Array(); //奇數位*2的積 <9
var arrJiShu2 = new Array(); //奇數位*2的積 >9
var arrOuShu = new Array(); //偶數位數組
for (var j = 0; j < newArr.length; j++) {
if ((j + 1) % 2 == 1) { //奇數位
if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
else arrJiShu2.push(parseInt(newArr[j]) * 2);
} else //偶數位
arrOuShu.push(newArr[j]);
}
var jishu_child1 = new Array(); //奇數位*2 >9 的分割之后的數組個位數
var jishu_child2 = new Array(); //奇數位*2 >9 的分割之后的數組十位數
for (var h = 0; h < arrJiShu2.length; h++) {
jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
}
var sumJiShu = 0; //奇數位*2 < 9 的數組之和
var sumOuShu = 0; //偶數位數組之和
var sumJiShuChild1 = 0; //奇數位*2 >9 的分割之后的數組個位數之和
var sumJiShuChild2 = 0; //奇數位*2 >9 的分割之后的數組十位數之和
var sumTotal = 0;
for (var m = 0; m < arrJiShu.length; m++) {
sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
}
for (var n = 0; n < arrOuShu.length; n++) {
sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
}
for (var p = 0; p < jishu_child1.length; p++) {
sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
}
//計算總和
sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
//計算luhn值
var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
var luhn = 10 - k;
if (lastNum == luhn) {
// $("#banknoInfo").html("luhn驗證通過");
return true;
} else {
// $("#banknoInfo").html("銀行卡號必須符合luhn校驗");
return false;
}
}
