0

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 :(
j08691
  • 204,283
  • 31
  • 260
  • 272
sbtn
  • 3
  • 1
  • 2

2 Answers2

2

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
rafaelgomesxyz
  • 1,405
  • 8
  • 14
  • This is exactly what I'm trying to do, validate the value as the user types in. Exactly what I was looking for. Thanks! – sbtn Mar 07 '18 at 18:26
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. See the answer above. I was looking for a way to validate the value as the user types in. – sbtn Mar 07 '18 at 18:32
  • That's going to get very complicated if you want to allow multiple types of credit cards. – Barmar Mar 07 '18 at 18:33