9

I found this simple function to return the 4 most common credit card types.

Being new to jQuery, what jQuery plugin can I use to display the credit card type as a user types in a credit card number in a input field?

 function creditCardTypeFromNumber(num) {
   // first, sanitize the number by removing all non-digit characters.
   num = num.replace(/[^\d]/g,'');
   // now test the number against some regexes to figure out the card type.
   if (num.match(/^5[1-5]\d{14}$/)) {
     return 'MasterCard';
   } else if (num.match(/^4\d{15}/) || num.match(/^4\d{12}/)) {
     return 'Visa';
   } else if (num.match(/^3[47]\d{13}/)) {
     return 'AmEx';
   } else if (num.match(/^6011\d{12}/)) {
     return 'Discover';
   }
   return 'UNKNOWN';
 }

Thank you!

floatleft
  • 6,243
  • 12
  • 43
  • 53

5 Answers5

4
$('#someTextBox').change(function() {
    $('#someOutput').text(creditCardTypeFromNumber($(this).val()));
});

This will output into some element with id="someOutput" the result of the text box which fires when the user changes the text in the element id="someTextBox".

MagExt
  • 222
  • 3
  • 16
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 6
    `change()` will not get fired until text input loses focus. Use keyup() instead for validation as you type – Hussein Mar 07 '11 at 02:58
  • I know is kinda old, but I was looking for something just like this. Just wanted to note, @Daniel A. White You need an extra ) at the end of line 2 ;) – stinkysGTI Nov 14 '14 at 18:32
1

jQuery Credit Card Type Detector Plugin https://github.com/christianreed/Credit-Card-Type-Detector

umpirsky
  • 9,902
  • 13
  • 71
  • 96
1

http://www.ihwy.com/labs/jquery-validate-credit-card-extension.aspx

http://docs.jquery.com/Plugins/Validation/Methods/creditcard

Plugins by default may not have the card validation as you type. To have realtime validation, you can bind a simple keyup() on the input field so validation is done after each key stroke.

Hussein
  • 42,480
  • 25
  • 113
  • 143
0

Also, FYI, the answer on this thread (link) has some regex for other card types, as well as an awesome explanation of credit card numbers.

Here's a function that only fires after they entered at least 6 digits (the ones used to recognize card type):

$('#CardNumber').keyup(function(){
   if($(this).val().length >= 6){
       cardType = creditCardTypeFromNumber($(this).val());
   }
});
Community
  • 1
  • 1
Joao
  • 2,696
  • 2
  • 25
  • 35
0

Use a free BIN API service like https://tripayments.com/bins/ . Submit the first 6 and it will give the "DetailCardProduct" which is VISA, Mastercard,etc

Spencer
  • 319
  • 5
  • 10