Posts Tagged ‘Software Development’

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:

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

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 "";
        }
</script>

Credit Card Regular Expression

November 7th, 2008

So for the project I’m currently working on I need to verify credit card numbers input by the user. So I found a regular expression online that would do almost all of it, but it lacked a few necessary validations such as Discover cards and 13-digit Visas. So I modified it to work with almost all forms of Visa, MasterCard, American Express, and Discover cards.

It also supports white space and dashes in between blocks of numbers, as would be found on an actual credit card.

Here it is:
^(((4\d{3})|(5[1-5]\d{2})|(6011))[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4})|(3[4,7][\d\s-]{13})|(4[\d\s-]{12})$

It’s not 100% perfect for catching invalid Discover or 13-digit Visa cards but it will recognize valid ones. For best results, strip out any non-digits from the input string before running it through the regular expression.

Cheers!