Creditcard verification with regex?

前端 未结 5 1056
星月不相逢
星月不相逢 2021-02-09 10:58

What is the right way to verify a credit card with a regex? If which one to use there are tons online. If not how to verify?

相关标签:
5条回答
  • 2021-02-09 11:01

    How can I use credit card numbers containing spaces? covers everything you should need.

    0 讨论(0)
  • 2021-02-09 11:09

    -- Edit:

    Infact, I'll slightly disagree with myself and agree with cletus. Validate as much as you can (without getting into details of specific types of credit cards [IMHO]) before sending it on. And it goes without saying (hopefully), that this validation should be done in JavaScript, to make it fast, then on the server, to double check (and for JavaScript disabled people).

    -- Previous Response:

    Don't bother; just let the provider verify it when you actually attempt payment. No legitimate reason to try and verify it yourself. You can use this though, if you really feel like it.

    0 讨论(0)
  • 2021-02-09 11:20

    I think you're looking for the Luhn Algorithm. It's a simple checksum formula used to validate a variety of identification numbers.

    0 讨论(0)
  • 2021-02-09 11:23

    See this link Finding or Verifying Credit Card Numbers with Regulars Expressions

    • Visa: ^4[0-9]{12}(?:[0-9]{3})?$ All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
    • MasterCard: ^5[1-5][0-9]{14}$ All MasterCard numbers start with the numbers 51 through 55. All have 16 digits.
    • American Express: ^3[47][0-9]{13}$ American Express card numbers start with 34 or 37 and have 15 digits.
    • Diners Club: ^3(?:0[0-5]|[68][0-9])[0-9]{11}$ Diners Club card numbers begin with 300 through 305, 36 or 38. All have 14 digits. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard, and should be processed like a MasterCard.
    • Discover: ^6(?:011|5[0-9]{2})[0-9]{12}$ Discover card numbers begin with 6011 or 65. All have 16 digits.
    • JCB: ^(?:2131|1800|35\d{3})\d{11}$ JCB cards beginning with 2131 or 1800 have 15 digits. JCB cards beginning with 35 have 16 digits.

    Bye.

    0 讨论(0)
  • 2021-02-09 11:23

    That depends on how accurate you want your pre-validation to be. To validate everything you can, you need to compute what the last digit of the card should be and compare to what is entered, which a RegEx cannot do.

    For the algorithm and other details see this link, which also provides a list of common number prefixes that you could validate against.

    0 讨论(0)
提交回复
热议问题