简体   繁体   中英

Credit card prediction in Javascript

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 (eg 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; } } } }); });​ 

Here's a fiddle

It seems like you're using the regular expressions in a wrong way.

If you want to check a string against a regular expression, you can use the match() method of the string:

string.match(regexp) // returns boolean

You're doing it the wrong way:

if ( regex.match($(this).val()) ) {

tries to interpret the current value as a regular expression. Must be this way:

if ( $(this).val().match(regex) ) {

You can also cache the regular expressions to make your script more efficient:

ccMap.cards = {
    'amex': /^3[47][0-9]{13}$/,  // store an actual regexp object, not a string
    // ...

// The way you test changes, now you're able to use the "test"
// method of the regexp object:
if ( regex.test($(this).val()) ) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM