Cómo comprobar una tarjeta de crédito con Javascript

A la hora de validar un formulario, todos sabemos que no es suficiente con utilizar código Javascript para ese fin, pero si una opción muy recomendable, ya que la validación del lado de cliente, impide que se hagan numerosas llamadas en el lado del servidor.

En nuestro caso, nos vamos a centrar en la validación de las tarjetas de crédito. Esto puede ser un gran problema para los desarrolladores, sobre todo cuando sólo se admiten tarjetas de crédito específicas.

Para facilitarnos esta tarea, Dojo Toolkit nos proporciona herramientas para ello, en concreto dojox.validate.creditCard, un recurso capaz de validar de manera eficiente una tarjeta de crédito. Mediante esta clase, usted podrá crearse su propias reglas de validación de forma sencilla.

El código de dojox.validate.creditCard es el siguiente. Viene muy bien comentado, pero está todo en inglés.

dojo.provide("dojox.validate.creditCard");
/*=====

        dojox.validate.creditCard = {
                // summary:
                //              Module provides validation functions for Credit Cards, using account number
                //              rules in conjunction with the Luhn algorigthm, with a plugable card info database.
        };
        
=====*/
dojo.require("dojox.validate._base");

dojox.validate._cardInfo = {
        // summary: A dictionary list of credit card abbreviations
        //
        // description:
        //
        //              A hash of valid CC abbreviations and regular expressions
        //
        //              mc: Mastercard
        //              ec: Eurocard
        //              vi: Visa
        //              ax: American Express
        //              dc: Diners Club
        //              bl: Carte Blanch
        //              di: Discover
        //              jcb: JCB
        //              er: Enroute
        //
        //      example:
        //              Define your own card, gift-card, whatever. Starts with 7,
        //              is 15 total length.
        //      | dojo.mixin(dojox.validate._cardInfo, {
        //      |       "my":"7[0-9]{14}"
        //      | });
        
        '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}'
}

dojox.validate.isValidCreditCard = function(value, ccType){
        // summary: Validate a credit card number by type with Luhn checking.
        //
        // description:
        //              Checks if a credit card type matches the # scheme in a passed value, and if
        //              the Luhn checksum is accurate (unless its an Enroute card, in which case
        //              the checkSum is skipped), returning a Boolean to check against.
        //
        // value: String|Int
        //              A Value (credit card number) to validate
        //
        // ccType: String
        //              A credit-card abbreviation.
        //
        // example:
        // |    if(dojox.validate.isValidCreditCard("12345", "mc")){
        // |            console.log('inconceivable');
        // |    }
        
        return ((ccType.toLowerCase() == 'er' || dojox.validate.isValidLuhn(value)) &&
                        dojox.validate.isValidCreditCardNumber(value, ccType.toLowerCase())); // Boolean
}

dojox.validate.isValidCreditCardNumber = function(value, ccType){
        // summary:
        //              Checks if value matches the pattern for that card or any card types if none is specified
        //
        // value: String|Int
        //              CC #, white spaces and dashes are ignored
        //
        // ccType: String?
        //              One of the abbreviation values in `dojox.validate._cardInfo` --
        //              if Omitted, function returns a `|` delimited string of matching card types,
        //              or false if no matches found.

        value = String(value).replace(/[- ]/g,''); //ignore dashes and whitespaces

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

        for(var p in cardinfo){
                if(value.match('^' + cardinfo[p] + '$')){
                        results.push(p);
                }
        }
        return results.length ? results.join('|') : false; // String | boolean
}

dojox.validate.isValidCvv = function(/* String|Int */value, /* String */ccType) {
        // summary:
        //      Validate the security code (CCV) for a passed credit-card type.
        //
        // description:
        //
        // value:
        
        if(!dojo.isString(value)){
                value = String(value);
        }
        var format;
        switch (ccType.toLowerCase()){
                case 'mc':
                case 'ec':
                case 'vi':
                case 'di':
                        format = '###';
                        break;
                case 'ax':
                        format = '####';
                        break;
        }
        
        return !!format && value.length && dojox.validate.isNumberFormat(value, { format: format }); // Boolean
}

Tu podrías hacer uso del anterior código pasando el número de la tarjeta y el tipo de esta, pero si no utizas Dojo Toolkit, no hay problema, ya que puedes sacar el código correspondiente a la validación, y utilizarlo en tu aplicación.

// Create an object
var creditCardValidator = {};
// Pin the cards to them
creditCardValidator.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 card validator to them
creditCardValidator.validate = function(value,ccType) {
        value = String(value).replace(/[- ]/g,''); //ignore dashes and whitespaces

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

        for(var p in cardinfo){
                if(value.match('^' + cardinfo[p] + '$')){
                        results.push(p);
                }
        }
        return results.length ? results.join('|') : false; // String | boolean
};

El siguiente paso sería hacer la llamada, pasándole el valor que queremos verificar.

if(!creditCardValidator.validate(document.id("creditCardField"))) {
        alert("Invalid credit card!");
}

 

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP