Posts Tagged ‘Credit Cards’

Determine Credit Card Type with Javascript

November 7th, 2008

I don’t understand why most online commerce sites ask the user to select what type of credit card they are going to enter instead of discerning the type programmatically and displaying feedback to the user. So here’s a small example I came up with on how to do just this.

Here’s a working example:

Here’s the HTML:

      <input id="ccNumber" onChange="SetTypeText(this.value)" />
      <br />
      <div id="cardType"></div>

Here’s the important part, the javascript:

<script type="text/javascript">
	function SetTypeText(number)
		var typeField = document.getElementById("cardType");
		typeField.innerHTML = GetCardType(number);
        function GetCardType(number)
            var re = new RegExp("^4");
            if (number.match(re) != null)
                return "Visa";
            re = new RegExp("^(34|37)");
            if (number.match(re) != null)
                return "American Express";
            re = new RegExp("^5[1-5]");
            if (number.match(re) != null)
                return "MasterCard";
            re = new RegExp("^6011");
            if (number.match(re) != null)
                return "Discover";
            return "";