Hatzi Hatzi - 4 months ago 29
Javascript Question

Identify card type from card number

i have an array of card types that looks something like this

var cards = new Array();

cards [0] = {name: "VISA", length: "13,16", prefixes: "4", checkdigit: true};
cards [1] = {name: "VISA_DELTA/ELECTRON", length: "16", prefixes: "417500,4917,4913", checkdigit: true};

however id like to be able to find the card type depending on the card number entered. e.g if they select their card type from a drop down list i.e visa, then the credit card number should start with 4 otherwise when they submit the form a message of some sort should be display saying this is (whatever card it is, please change card type). Any help would be appreciated.

the id for the card number text field is CardNumber. Im not sure what other info may be needed, i have a function called Validate which validates the rest of the form and a function call Calculate which does the luhn check.


I believe you are probably looking for something like this:

<script type="text/javascript">
function GetCardType(number)
    // visa
    var re = new RegExp("^4");
    if (number.match(re) != null)
        return "Visa";

    // Mastercard
    re = new RegExp("^5[1-5]");
    if (number.match(re) != null)
        return "Mastercard";

    // AMEX
    re = new RegExp("^3[47]");
    if (number.match(re) != null)
        return "AMEX";

    // Discover
    re = new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)");
    if (number.match(re) != null)
        return "Discover";

    // Diners
    re = new RegExp("^36");
    if (number.match(re) != null)
        return "Diners";

    // Diners - Carte Blanche
    re = new RegExp("^30[0-5]");
    if (number.match(re) != null)
        return "Diners - Carte Blanche";

    // JCB
    re = new RegExp("^35(2[89]|[3-8][0-9])");
    if (number.match(re) != null)
        return "JCB";

    // Visa Electron
    re = new RegExp("^(4026|417500|4508|4844|491(3|7))");
    if (number.match(re) != null)
        return "Visa Electron";

    return "";

Originally posted here @ http://mel-green.com/2008/11/determine-credit-card-type-with-javascript/