I'm writing a tool that onkeydown will run the current value being entered in an input box to check to see if it matches a regex for one of the 4 major types of credit cards.
I feel like it kind of works, but it's flaky so I wanted to figure out what was causing it to give faulty response (e.g. sometimes it'll output 2 values instead of one). Is it because I need to set a flag variable before looping? Upon match of the correct card, I'm just returning from the loop through the object, so I thought that'd be sufficient enough...
The criteria for the regexes were pulled from this site:
Visa:
^4[0-9]{12}(?:[0-9]{3})?$
All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.MasterCard:
^5[1-5][0-9]{14}$
All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.American Express:
^3[47][0-9]{13}$
American Express card numbers start with 34 or 37 and have 15 digits.Discover:
^6(?:011|5[0-9]{2})[0-9]{12}$
Discover card numbers begin with 6011 or 65. All have 16 digits.$(function() { var $cardNumber = $('#js-cardnumber'); var ccMap = {}; ccMap.cards = { 'amex': '^3[47][0-9]{13}$', 'discover': '^6(?:011|5[0-9]{2})[0-9]{12}$', 'mastercard': '^5[1-5][0-9]{14}$', 'visa': '^4[0-9]{12}(?:[0-9]{3})?$' }; $cardNumber.keydown(function() { for (var cardType in ccMap.cards) { if (ccMap.cards.hasOwnProperty(cardType)) { var regex = ccMap.cards[cardType]; if (regex.match($(this).val())) { console.log(cardType); return; } } } }); });