Quick actions

cmd+k|ctrl+k

Navigation

Languages

Luhn Validator

Snippet info

Language

JavaScript

Visibility

public

Author

horngyih

Created

2017-11-20T09:44:38Z

Updated

2017-11-20T10:34:22Z


//Information Source
// https://www.freeformatter.com/credit-card-number-generator-validator.html
function luhnValidate( target ){
    if( target ){
        target = "" + target;
        var digits = target.split("");
        var lastDigit = parseInt(digits.splice(digits.length-1)[0]);
        var result = digits.reverse()
        .map(function(item,index){
            var result = parseInt(item);
            if( (index + 1)%2 == 1 ){
                result = result * 2;
            }
            if( result > 9 ){
                result -= 9;
            }
            return result;
        })
        .reduce(function(accumulator,item){
            return accumulator + item;
        },0);
        return modulo(result,10) === lastDigit;        
    } else {
        return false;
    }
}

function modulo( target, mod ){
    if( target && mod ){
        return (mod-(target%mod))%mod;
    } else {
        return target;
    }
}


var VisaClassification = {
    classification : 'VISA',
    length : [13,16,19],
    regex : /^4.+/
};

var MastercardClassification = {
    classification : 'MASTER',
    length : [16],
    regex : /^5[1-5].+/
};

function classify( target, classification ){
    if( target && classification ){
        target = ""+target;
        if( classification.length && classification.regex ){
            var length = classification.length;
            if( !Array.isArray(length) ){
                length = [].push(length);
            }
            var lengthTest = length.
                map(function(item){
                    return target.length === item;
                }).
                reduce(function(result,item){
                    return result || item;
                },false);
            var iinTest = classification.regex.test(target);
            if( lengthTest && iinTest ){
                return classification.classification;
            } else {
                return null;
            }
        }
    }
}

var classifications = [
    VisaClassification,
    MastercardClassification
];

var targets = [
    "4556737586899855",
    "4111111111111111",
    4444333322221111,
    "5105105105105100",
    "5504182320730498"
];

targets.forEach(function(target){
    var classified = classifications.map(function(classification){
        return classify(target, classification);
    }).filter(function(item){return item});
    console.log( target, " ", (luhnValidate(target))?"Valid":"Invalid", classified);
});
INFO