Credit Card Prediction in Javascript

I am writing a tool that onkeydown will run the current value entered in an input field to check if it matches the regular expression for one of the four main types of credit cards.

I feel that this somehow works, but it is uneven, so I wanted to find out what made him give an erroneous answer (for example, sometimes it outputs 2 values ​​instead of one). Is it because I need to set the flag variable before the loop? After matching the correct map, I just return from the loop through the object, so I thought that would be enough ...

Criteria for regular expressions were extracted from this site :

  • Visa : ^4[0-9]{12}(?:[0-9]{3})?$All Visa card numbers start with 4. New cards have 16 digits. Old cards have 13.

  • MasterCard : ^5[1-5][0-9]{14}$All MasterCard numbers start with numbers 51 through 55. All have 16 digits.

  • American Express : American Express^3[47][0-9]{13}$ card numbers start at 34 or 37 and have 15 digits.

  • Open : ^6(?:011|5[0-9]{2})[0-9]{12}$Card number discovery starts 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 is the violin

+5
source share
1 answer

It looks like you are using the wrong regular expression.

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

string.match(regexp) // returns boolean

You are doing it wrong:

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

. :

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

, script :

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()) ) {
+4

All Articles