Search code examples
javascriptregexcredit-card

Regex - Credit Card validation


I'm looking for a way to validate the beginning of a credit card pattern. So for example, let's take MasterCard.

It says that (ref: https://www.regular-expressions.info/creditcard.html):

MasterCard numbers either start with the numbers 51 through 55...

I'm looking for a regex that returns true when the user enters:

const regex = /^5|5[1-5]/; // this is not working :(

regex.test("5"); // true
regex.test("51"); // true
regex.test("55"); // true
regex.test("50"); // should be false, but return true because it matches the `5` at the beginning :(


Solution

  • Are you validating as the user types in? If so, you could add an end of line ($) to the first option, so that it returns true only if:

    • 5 is the only character typed so far
    • The string begins with 50-55

    const regex = /^(5$|5[1-5])/;
    
    regex.test("5"); // true
    regex.test("51"); // true
    regex.test("55"); // true
    regex.test("50"); // false