# Checksum algorythm

i have this luhn-mod n checksum algorythm in javascript code which generates a 15 alphanumeric string and calculates a checksum at the end. i want to apply this formula to my records in a field. can u help me out?

this is the code:

(function(){
var possible = ‘0123456789abcdefghijklmnopqrstuvwxyz’;

``````function randomString(length) {
var text = '';

for( var i=0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}

return text;
}

function generateCheckCharacter(input) {

var factor = 2;
var sum = 0;
var n = possible.length;

// Starting from the right and working leftwards is easier since
// the initial "factor" will always be "2"
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = possible.indexOf(input.charAt(i));
var addend = factor * codePoint;

// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;

// Sum the digits of the "addend" as expressed in base "n"
}

// Calculate the number that must be added to the "sum"
// to make it divisible by "n"
var remainder = sum % n;
var checkCodePoint = (n - remainder) % n;

return possible.charAt(checkCodePoint);
}

function isValid(input) {

var factor = 1;
var sum = 0;
var n = possible.length;

// Starting from the right, work leftwards
// Now, the initial "factor" will always be "1"
// since the last character is the check character
for (var i = input.length - 1; i >= 0; i--) {
var codePoint = possible.indexOf(input.charAt(i));
var addend = factor * codePoint;

// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;

// Sum the digits of the "addend" as expressed in base "n"
}

var remainder = sum % n;

return (remainder == 0);
}

\$('#validate').click(function() {
\$('#isValid').text(isValid(\$('#result').val()));
});

\$('#generate').click(function() {
var prefix = randomString(15);
var check = generateCheckCharacter(prefix);

\$('#result').val(prefix + "-" + check);
\$('#isValid').text(isValid(\$('#result').val()));
});
``````

})();

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.