1

I have the following code that validates if a certain digits is valid using luhn algorithm module 10.

function isCheckdigitCorrect(value) {
// accept only digits, dashes or spaces
  if (/[^0-9-\s]+/.test(value)) return false;

  var nCheck = 0, nDigit = 0, bEven = false;
  value = value.replace(/\D/g, "");

  for (var n = value.length - 1; n >= 0; n--) {
    var cDigit = value.charAt(n),
      nDigit = parseInt(cDigit, 10);

    if (bEven) {
      if ((nDigit *= 2) > 9) nDigit -= 9;
    }

    nCheck += nDigit;
    bEven = !bEven;
  }

  return (nCheck % 10) == 0;
}

I need another function that generates the next check-digit actually by giving four digit number so the 5th digit would be next digit checksum.

Spitz
  • 79
  • 1
  • 3
  • 10
pranvera hoti
  • 107
  • 3
  • 15

1 Answers1

3

By modifying the current function to this one I was able to get next checkdigit:

function getCheckDigit(value) {
  if (/[^0-9-\s]+/.test(value)) return false;

  var nCheck = 0, nDigit = 0, bEven = true;
  value = value.replace(/\D/g, "");

  for (var n = value.length - 1; n >= 0; n--) {
    var cDigit = value.charAt(n),
      nDigit = parseInt(cDigit, 10);

    if (bEven) {
      if ((nDigit *= 2) > 9) nDigit -= 9;
    }

    nCheck += nDigit;
    bEven = !bEven;
  }
  return (1000 - nCheck) % 10;
}
pranvera hoti
  • 107
  • 3
  • 15
  • Perfecto! Good to see you answered a question for the first time, you can also accept your answer as the correct answer. Stack Overflow is an open community, it's why I like it. +1 for you – Mohammad Kermani Apr 24 '17 at 12:47