2016-08-12 3 views
-1

Luhn 수식을 기반으로하는 자바 스크립트로 신용 카드 번호의 유효성을 검사하려고합니다. 이것에 대한 플러그인이 있다는 것을 알고 있지만, 내 자신 만의 샷을주고 싶었습니다. 나는 유효한 것으로 생각되는 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