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.

8
  • "I need another function" I understand, but can you post what have you tried so far? Commented Apr 24, 2017 at 11:52
  • Take a look at gist.github.com/DiegoSalazar/4075533 Commented Apr 24, 2017 at 11:55
  • @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! Commented Apr 24, 2017 at 11:55
  • 1
    @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 Commented Apr 24, 2017 at 11:56
  • 1
    @M98 Ohh I see the comments below are telling how to generate one, worked, thnx :) Commented Apr 24, 2017 at 11:57

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.