title: Credit card prediction in Javascript
body: <p>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.</p>
  
  <p>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...</p>
  
  <p>The criteria for the regexes were pulled from <a href="http://www.regular-expressions.info/creditcard.html" rel="noreferrer">this site</a>:</p>
  
  <ul>
  <li><p><strong>Visa</strong>: <code>^4[0-9]{12}(?:[0-9]{3})?$</code> All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.</p></li>
  <li><p><strong>MasterCard</strong>: <code>^5[1-5][0-9]{14}$</code> All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.</p></li>
  <li><p><strong>American Express</strong>: <code>^3[47][0-9]{13}$</code> American Express card numbers start with 34 or 37 and have 15 digits.</p></li>
  <li><p><strong>Discover</strong>: <code>^6(?:011|5[0-9]{2})[0-9]{12}$</code> Discover card numbers begin with 6011 or 65. All have 16 digits.</p>
  
  <pre><code>$(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;
          }
      }
  }
  });
  });​
  </code></pre></li>
  </ul>
  
  <p><a href="http://jsfiddle.net/someprimetime/ThzXG/" rel="noreferrer">Here's a fiddle</a></p>