Determine the card type based on the card number

My array of card types is structured 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};

I want to be able to identify the card type based on the entered credit card number. For instance, if a user selects "VISA" from a dropdown list, the card number should start with 4. If not, display a message asking the user to change the card type before submitting the form. Any assistance on this matter would be greatly appreciated.

The ID for the card number text field is CardNumber. I also have functions named Validate for form validation and Calculate for performing the Luhn check.

Answer №1

Here is a helpful code snippet that can assist you in determining the type of credit card:

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

    // Mastercard 
    // Updated for Mastercard 2017 BINs expansion
     if (/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(number)) 
        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 "";
}
</script>

You can find the original source of this code here.

Answer №2

Check out this amazing jQuery plugin specifically designed for this purpose:

For a detailed discussion on how credit card numbers are linked to card types, take a look at this insightful StackOverflow answer:

Answer №3

Card companies have specific prefixes assigned to each card type.

These prefixes can range from a single digit (all starting with '5' are Mastercard) to longer strings of up to six or seven digits for more uncommon card types. They can also help identify the issuing bank.

One helpful resource I came across is:

You might also find Wikipedia useful: http://en.wikipedia.org/wiki/Credit_card_numbers

The challenge is that although the current prefixes are fairly consistent, there's always a chance that new ones will be introduced. It's important to keep your prefix list updated, especially if you're using it to check longer ranges of prefixes.

Answer №4

The card prefix system is outlined in lists of BIN (bank identification number) and is subject to frequent changes. I would recommend avoiding validation based on the complete first 6 digits of the PAN unless you are willing to regularly update your data, and instead focus on a basic check of the initial couple of digits (e.g., the missing 48* for Visa/Electron, which can range from 16 to 19 digits in length).

If you are located in the United Kingdom, you can refer to this link for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The HTML required attribute seems to be ineffective when using AJAX for form submission

Having trouble with HTML required attribute when using AJAX submission I have set the input field in a model Form to require attribute, but it doesn't seem to work with ajax. <div class="modal fade hide" id="ajax-book-model" a ...

What could be causing my if-else statement to malfunction in JavaScript?

I'm working on a form where certain conditions need to be met based on the selected order type. For instance, if a market order is chosen, the stop price and limit price should default to zero and become read-only fields. Similarly, selecting a limit ...

Does every controller page need to verify the Login Function?

In my PHP pages, I have implemented the MVC Pattern by creating a controller page for each view page to interact with the Model page. However, I have only checked user login at the top of every view page and not in the controller page. This leaves a potent ...

Issue with webcomponents-lite.js file

Encountering this particular error message in the console while attempting to run the application: webcomponents-lite.js:64Uncaught TypeError: Cannot read property 'getAttribute' of null at webcomponents-lite.js:64 at Object.549 (webcomp ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below: "data":[ ["1951","306","27","159","34","82","4"], ["1956","426","41","203","47","119","16"], ["1959","562","67"," ...

Localizing Dates in JavaScript

I'm currently dealing with localization and globalization in an ASP.NET application. As I navigate through this process, I am encountering difficulties in getting the Date() function in JavaScript to function correctly based on the user's locatio ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Determine the number of stored values in a specific key by utilizing stringify within localstorage

Is there a way to determine the number of unique values stored under one key in local storage? For instance: Here is the content of my local storage: [{"id":"item-1","icon":"google.com"},{"id":"item-2","icon":"youtube.com"}] In this case, I would like ...

What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this: $scope.StateList = {"States": [ { "Id": 1, "Code": "AL", "Name": "Alabama" }, { "Id": 2, "Code": "AK", "Name": "Alask ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Updating Input Field with AngularJS Date Format During Input Field Change

Here is the input field for date: <div class="input-group date"> <input type="text" class="form-control" id="datepicker" placeholder="dd/mm/yyyy" ng-model="abs.date"> </div> The value in this field is updated ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL. The JSON data looks something like this: {"marketcode":"01","size":"8,5", ...

Discovering repeated values and verifying the value range within table columns can be achieved through the use

Within my table, I have two columns labeled Min Range and Max Range. My objective is to identify duplicate values within these columns while ensuring that no row definition overlaps another. The image below illustrates this concept: https://i.sstatic.net/ ...

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...