2016-08-12 4 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