Help

The Community will be temporarily unavailable starting on Friday February 28. We’ll be back as soon as we can! To learn more, check out our Announcements blog post.

Checksum algorythm

1058 0
cancel
Showing results for 
Search instead for 
Did you mean: 
Andreas_Iacovid
6 - Interface Innovator
6 - Interface Innovator

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"
            addend = Math.floor(addend / n) + (addend % n);
            sum += addend;
    }

    // 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"
            addend = Math.floor(addend / n) + (addend % n);
            sum += addend;
    }

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

})();

0 Replies 0