Search code examples
javascriptchecksumluhncheck-digit

I need to validate an input string using checksum for alphanumerics


I have the following function that validates a digits input consisted of only numbers based on Luhn Algorithm:

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

Is there anyway that I can validate also alphanumerics, so let's suppose I have a valid ID: AC813(6) , () is the checksum. So is there a way that I can prevent users having to type mistakenly AF813(6) so this would tell user incorrect ID.

I appreciate your help


Solution

  • If you just want to do the Luhn algorithm with letters replacing some of the numbers, then include an additional step to convert letters to numbers within your function.

    So if you wanted to allow say A, B, C, D that convert to 0, 1, 2, 3 then you could do:

    function isCheckdigitCorrect(value) {
    
      // Letter to number mapping
      var letters = {a:'0', b:'1', c:'2', d:'3'};
      
      // Convert letters to their number equivalents, if they have one
      value = value.split('').reduce(function(s, c){
        return s += letters[c.toLowerCase()] || c;
      },'');
    
      // Continue as currently
      // 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;
    }
    
    // In the following, A = 0 and D = 3
    console.log(isCheckdigitCorrect('375767AA4D6AA21'));

    You can implement other algorithms in a similar way.