CC 验证 (LuhnFormula) 错误

CC validation (LuhnFormula) Errors

我正在尝试根据 Luhn 公式使用 Javascript 验证信用卡号。我知道有这方面的插件,但我想自己试一试。我已经包含了一个应该有效的 test credit card number。不幸的是,我得到了无效的结果。所以,我猜我在逻辑上犯了一个错误。我正在寻求一些帮助,看看我可能哪里出错了。

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:非常感谢任何帮助。

这是稍微修改过的 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)" />