Card number verification

Each payment card has its own unique number. Banks have databases of all card numbers, but polling them is extremely time consuming. At the same time, the internet is teeming with typos and scams. Therefore, banks need your algorithm to verify the card number in the browser. The number of the card issued by the selected supplier always has a specific length:

  • Mastercard: 16 digits.
  • Visa: 13 or 16 digits.
  • American Express: 15 digits.

These numbers start with a defined pool of numbers:

  • Mastercard: 51, 52, 53, 54, 55
  • Visa: 4
  • American Express: 34, 37

In addition, the card number, regardless of the provider, must be verified using the Luhn algorithm:

  1. Starting with the penultimate number, multiply by two each digit with an odd index. Break it up obtained numbers into the sum of their digits (e.g. 18 -> 1 + 8), then sum all these digits together.
  2. Add the sum obtained to the sum of the digits that you did not multiply by two.
  3. If the received number modulo 10 is 0, the card number is valid.