Simple Js to detect Credit Card type, and select CardType img accordingly

HTML

<img id=’MC’ src=’MC.png’ class=’cardimg’ /><img id=’VA’ src=’VA.png’ class=’cardimg’ /><img id=’DC’ src=’DC.png’ class=’cardimg’ /><img id=’JC’ src=’JC.png’ class=’cardimg’ /><img id=’AX’ src=’AX.png’ class=’cardimg’ />

<input type=’text’ id=’txtCardNumber’ onclick=’ShowHideCreditCardPanel2(this.value);’ />

 

Javascript (Uses JQuery to enumerate of list of card type images)

function selectCardImg(cardNumber)
{

         // STEP 1. detect card type
         var cardType = detectCreditCardType(cardNumber);

 

         // STEP 2. select appropriate card type image

$(‘.cardimg’).each(function (index, value) {
   var Id = $(this).attr(‘id’);
   $(this).removeClass(‘cardimg-selected’);
   if(Id==cardType)
      {
          $(this).addClass(‘cardimg-selected’);
      }
   }
)
}

function detectCreditCardType(cardNumber)
{
   var cardType = “”;

   if (/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/.test(cardNumber))
   {
      cardType = “MC”;
   }
   else if (/^3[0,6,8]\d{12}$/.test(cardNumber))
   {
      cardType = “DC”;
   }
   else if (/^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/.test(cardNumber))
   {
      cardType = “VA”;
   }
   else if (/(^(352)[8-9](\d{11}$|\d{12}$))|(^(35)[3-8](\d{12}$|\d{13}$))/.test(cardNumber))
   {
      cardType = “JC”;
   }
   else if (/^3[4,7]\d{13}$/.test(cardNumber))
   {
      cardType = “AX”;
   }

      return cardType ;
   }

 

Reference: http://blogs.markglibres.com/2010/10/c-get-credit-card-type.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s