1
votes

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.

1
"I need another function" I understand, but can you post what have you tried so far? - evolutionxbox
@evolutionxbox i havent tried anything yet cz I have no idea how to achieve that, actually i tried the same function and modified a litle bit but had no luck with it! - pranvera hoti
@M98 this is what I already have actually, this function checks if the digits are valid based on luhn algorithm, I need to create digits including the checksum - pranvera hoti
@M98 Ohh I see the comments below are telling how to generate one, worked, thnx :) - pranvera hoti

1 Answers

3
votes

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;
}