Search code examples
angularjsregexcredit-card

Regex pattern to support the 19 digit Visa and Discover card validation


Currently i am using the following regex, but they are not supporting 19 digit cards for both visa and discover. Kindly help.

 visaCardPattern: /^4[0-9]{12}(?:[0-9]{3})?$/

discoverCardPattern: /^6(?:011|5[0-9]{2})[0-9]{12}$/

Solution

  • For the VISA - all you have to do is simply make the optional [0-9] group match either one, or two times.

    ^4[0-9]{12}(?:[0-9]{3}){0,2}$
    

    Essentially this is the same as the regex you already had, except the optional [0-9]{3} group now has 3 possible outcomes-

    • It doesn't get matched at all - 13 digits VISA
    • It gets matched once - 16 digits VISA
    • It gets matched twice - 19 digits VISA

    Check out the demo here

    For the discover card - it's even more simple, you simply have to add a upper bound to the [0-9]{12}.

    Since discover cards can have a length between 16 to 19 (inclusive), you simply have to change your regex to-

    ^6(?:011|5[0-9]{2})[0-9]{12,15}$
    

    This is the same as your own regex except that the final 0-9 group now has the following outcomes-

    • It matches 12 times - total length will be 16
    • It matches 13 times - total length will be 17
    • It matches 14 times - total length will be 18
    • It matches 15 times - total length will be 19

    Check out the demo here

    Note: This is under the assumption that discover cards can have a length between 16 and 19, not either 16 or 19. Some sources say it can have any length in between, whereas some say it can only have either 16 or 19.

    I'm not credit card expert, but for the sake of completion, I'll include a regex to match either 16 or 19 for the discover cards too-

    ^6(?:011|5[0-9]{2})(?:[0-9]{3}){4,5}$
    

    This one matches the final [0-9] in groups of 4, with the following outcomes-

    • It gets matched 4 times - total of 16 digits
    • It gets matched 5 times - total of 19 digits

    Check out the demo here

    Edit: For mastercard, you can try this-

    ^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)(?:[0-9]{3}){4,5}$
    

    Exactly the same method as the discover card, just match the final [0-9] in groups of 3 and make it match either 4 or 5 times. (aka either 4 times for a total of 16 digits and 5 times for a total of 19)

    Check out the demo here