Validate credit card with js

Asked

Viewed 11,096 times

3

I would like to know how to validate the credit card through Js.

Visa starts with 4 Mastercard starts with 51, 52, 53, 54 or 55; American Express starts at 34 and 37

Someone knows the best way to validate this?

<fieldset class="fsResDir">
    <legend>Dados do Cartão&nbsp;</legend>
    <input type="radio" name="RadBand" id="visa" checked />
    <label for="visa">
      <img src="visa.png" />
    </label>
    <input type="radio" name="RadBand" id="mast" />
    <label for="mast">
      <img src="master.png" />
    </label>
    <input type="radio" name="RadBand" id="amex" />
    <label for="amex">
      <img src="amex.png" />
    </label>
    <label for="val" class="lab90">Validade:</label>
    <input type="text" class="ent20Form" id="val" name="TxtValMes" />/
    <input type="text" class="ent40Form" name="TxtValAno" />
    <label for="num" class="lab90">Numero:</label>
    <input type=text class="ent120Form" id="num" name="TxtNumero" />
  </div>
</fieldset>

1 answer

10


Here is a suggestion:

var cartoes = {
    Visa: /^4[0-9]{12}(?:[0-9]{3})/,
    Mastercard: /^5[1-5][0-9]{14}/,
    Amex: /^3[47][0-9]{13}/,
    DinersClub: /^3(?:0[0-5]|[68][0-9])[0-9]{11}/,
    Discover: /^6(?:011|5[0-9]{2})[0-9]{12}/,
    JCB: /^(?:2131|1800|35\d{3})\d{11}/
};

function testarCC(nr, cartoes) {
    for (var cartao in cartoes) if (nr.match(cartoes[cartao])) return cartao;
    return false;
}

var valido = '4444555566667777';
var invalido = '1234567890';

[valido, invalido].forEach(function(teste){
   console.log(testarCC(teste, cartoes)); 
});

// dá VISA, false

jsFiddle: http://jsfiddle.net/tdLL7qy2/

The idea of this function is to go through the regex of each card and return the name of the card, or false if no pattern is valid.

  • I understood, it would be possible to automatically mark a radiobox related to the flag of the card. Instead of validating?

  • @ygorbr yes. What is the HTML in this case?

  • I edited the post with the html code

  • @ygorbr is what you’re looking for? http://jsfiddle.net/tdq8os3d/

  • Yes, but I think I need a repair. But I believe the basis is this msm. The idea is to automatically change it as soon as a number is entered. Thank you my friend

  • Helped me a lot

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.