2016-08-12 36 views
-1

我想驗證基於Luhn公式的JavaScript的信用卡號碼。我意識到有這個插件,但是想自己試試。我已經包含了一個應該是有效的test credit card number。不幸的是,我收到了無效的結果。所以,我猜我在邏輯上犯了一個錯誤。我正在尋找一些幫助,看看我可能出錯的地方。CC驗證(LuhnFormula)錯誤

var ccNumber = "5185763365093706"; 
var finalArray = []; 
var lastNumber; 

function validateCC() { 
    // convert CCNumber to array 
    var ccArray = ccNumber.split(""); 
    // Remove the last number from the array, and store it as a number in a variable 
    lastNumber = ccArray.pop() * 1; 

    var ccReverse = Array.prototype.slice.call(ccArray).reverse(); 

    for(var i = 0; i < ccReverse.length; i++) { 
    var newNumber; 

    // for all the odd numbers in the 
    if(i %2 === 0) { 
     // multiply each odd numbered array item by 2 
     var newCalc = ccReverse[i] * 2; 
     var finalCalc; 

     // check to see if the resulting calculation is greater than 9 
     (function() { 
     if(newCalc > 9) { 
      finalCalc = newCalc - 9; 
     } else { 
      finalCalc = newCalc; 
     } 
     })(); 
     // push each odd number to the finalArray 
     finalArray.push(finalCalc); 
    } 
    } 
} 

validateCC(); 

// Add up all the numbers in the final array 

var total = (finalArray.reduce(addArray, 0)); 

function addArray(a, b) { 
return a + b; 
} 

// The number above should be valid, but it's returning false. 
if(total % 10 === lastNumber) { 
    console.log("Is a valid credit card"); 
} else { 
    console.log("Is not a valid credit card"); 
} 

我也有很多評論jsbin:任何幫助,非常感謝。

回答

0

這是一個有點修改的Luhn公式實現。

function validateCC(elem){ 
 
    var s = elem.value.replace(/\D/g, '')//sanitize 
 
     .split('')//produce array 
 
     .reverse(); 
 
    if (!s.length || s.length < 15 || s.length > 16) {//15 for AmEx 16 for others 
 
    console.log('validation failed'); 
 
    return false; 
 
    } 
 
    //1st element is not excluded so final sum % 10 must be 0 
 
    var v = "";//string for sure 
 
    for (var i = 0, n = s.length; i < n; ++i) { 
 
    //no need "- 9" 
 
    //for example 8 * 2 = 16 
 
    //16 - 9 = 7 
 
    //1 + 6 = 7 
 
    v += s[i] * ((i % 2) + 1);//concatenate string 
 
    } 
 
    s = v.split('');//reuse var 
 
    v = 0;//this time int 
 
    i = 0; 
 
    while (!isNaN(s[i])) { 
 
    v += (s[i++] - 0);//- 0 for parseInt 
 
    } 
 
    if (v == 0 || v % 10) {//all 0000 fail 
 
    console.log('validation failed'); 
 
    return false; 
 
    } 
 
    console.log('Card is valid'); 
 
    return true; 
 
    }
<input type="text" onchange="validateCC(this)" />

+0

感謝您的反饋意見。我會看一下,看看我可以如何根據你發佈的例子進行改進。 – somecallmejosh