sbtn
sbtn

Reputation: 3

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 :(

Upvotes: 0

Views: 2981

Answers (2)

Barmar
Barmar

Reputation: 782216

It should be:

const regex = /^5[1-5]/;

Your regex matches either a string beginning with 5 or a string that has 51 through 55 anywhere in it, because the ^ is only on the left side of the |.

If you want to allow a partial entry, you can use:

const regex = /^5(?:$|[1-5])/;

See Validating credit card format using regular expressions? for a regular expression that matches most popular cards.

Upvotes: 0

rafaelgomesxyz
rafaelgomesxyz

Reputation: 1405

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

Upvotes: 2

Related Questions