JSFiddle - React, Tailwind, and code Playground

by silvinci

JavaScript

// Create an object
var creditCardValidator = {
    // Pin the cards to them
    'cards': {
        'mc':    '5[1-5][0-9]{14}',
        'ec':    '5[1-5][0-9]{14}',
        'vi':    '4(?:[0-9]{12}|[0-9]{15})',
        'ax':    '3[47][0-9]{13}',
        'dc':    '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
        'bl':    '3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
        'di':    '6011[0-9]{12}',
        'jcb':    '(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
        'er':    '2(?:014|149)[0-9]{11}'
    },
    // Add the structure validator to them
    'validateStructure': function(value, ccType) {
        value = String(value).replace(/[^0-9]/g, ''); // ignore dashes and whitespaces - We could even ignore all non-numeric chars (/[^0-9]/g)

        var cardinfo = creditCardValidator.cards,
            results  = [];
        if(ccType){
            var expr = '^' + cardinfo[ccType.toLowerCase()] + '$';
            return expr ? !!value.match(expr) : false; // boolean
        }

        for(var i in cardinfo){
            if(value.match('^' + cardinfo[i] + '$')){
                results.push(i);
            }
        }
        return results.length ? results.join('|') : false; // String | boolean
    },
    // Add the Luhn validator to them
    'validateChecksum': function(value) {
        value = String(value).replace(/[^0-9]/g, ''); // ignore dashes and whitespaces - We could even ignore all non-numeric chars (/[^0-9]/g)
        
        var sum        = 0,
            parity    = value.length % 2;
        
        for(var i = 0; i <= (value.length - 1); i++) { // We'll iterate LTR - it's faster and needs less calculating
            var digit = parseInt(value[i], 10);
            
            if(i % 2 == parity) {
                digit = digit * 2;
            }
            if(digit > 9) {
                digit = digit - 9; // get the cossfoot - Exp: 10 - 9 = 1 + 0 | 12 - 9 = 1 + 2 | ... | 18 - 9 = 1 + 8
            }
            
            sum += digit;
        }
        
     ...