javascript – Validate credit card with js


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 with 34 and 37

Does anyone know how best 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" />
    <input type="radio" name="RadBand" id="mast" />
    <label for="mast">
      <img src="master.png" />
    <input type="radio" name="RadBand" id="amex" />
    <label for="amex">
      <img src="amex.png" />
    <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" />


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


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

Scroll to Top