Others



How to Validate Debit or Credit Card Number using JavaScript Regular Expression


A Debit or Credit card number is a sequence of Digits with a specific formats. But there is no common format in the debit or credit card numbering system. We can change a Regular Expression format for various cards. We have to validate following three cards with JavaScript Regular Expression.

  • Master Card Starting 51-55, Length 16 Digits
  • Visa Card Starting 4, Length 13 or 16 Digits
  • American Express Card Starting 34 or 37, Length 15 Digits
RegEx Fromat
var masterCardRegex=/^(?:5[1-5][0-9]{14})$/;
var visaCardRegex=/^(?:4[0-9]{12})(?:[0-9]{3})$/;
var americanExpCardRegex=/^(?:3[47][0-9]{13})$/;

The following example shows, how to validate debit or credit card Number using JavaScript Regular Expression.

Example
<html>
  <body>
    <input type='text'  onkeyup="card_validate(this)" placeholder="Enter Card No">
    <p id='out'></p>
    <script>
      function card_validate(ele){
        var cardNo=ele.value;
        var masterCardRegex=/^(?:5[1-5][0-9]{14})$/;
        var visaCardRegex=/^(?:4[0-9]{12})(?:[0-9]{3})$/;
        var americanExpCardRegex=/^(?:3[47][0-9]{13})$/;
        
        var cardName="-";
        if(masterCardRegex.test(cardNo)){
          cardName="Master Card";
        }else if(visaCardRegex.test(cardNo)){
          cardName="Visa Card";
        }else if(americanExpCardRegex.test(cardNo)){
          cardName="American Express Card";
        }
        document.querySelector("#out").innerText=cardName;
      }
    </script>
  </body>
</html>
Try it Yourself

Demo