-1

I want to validate card expiration date on format MM/YY, MM should have values from 01 to 12 and YY from 19 to 99.

This is my code:

^(0[1-9]|10|11|12)/1[9]|2[0-9]{2}$

The MM part seems to work fine but the YY doesn't. It only take 19 as valid but also if I add new digits after that it says it's valid.

I was expecting to not validate if there are more than 2 digits for YY because of {2}.

How should it be changed in order to validate all years from 19 to 99 ?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • @WiktorStribiżew, still doesn't work. I checked for `11/19`, `11/20` and fails for both. I've tested it here https://regex101.com/ but still not working – Leo Messi Sep 09 '20 at 12:05
  • 1
    You missed the grouping construct anyway, `1[9]|2[0-9]` must be wrapped with a group, `(1[9]|2[0-9])`. The `{2}` can be removed. `^(0[1-9]|10|11|12)\/(1[9]|2[0-9])$` already [works](https://regex101.com/r/PSGWTg/1). – Wiktor Stribiżew Sep 09 '20 at 12:13

2 Answers2

0

This may works for your need:

^(?:0[1-9]|1[0-2])\/(?:19|[2-9][0-9])$

Demo: https://regex101.com/r/FrZJKU/1

Explanation:

^               Line start with...
 (?:            > Start non-capturing group
    0[1-9]      January to September
          |     OR
    1[0-2]      October to December
  )             > End non-capturing group
\/              literal '/'
  (?:           > Start non-capturing group
     19         literal '19'
       |        OR
     [2-9][0-9] 20 to 99
  )             > End non-capturing group
$               line must end with 20 to 99
Sumak
  • 927
  • 7
  • 21
  • 1
    A good answer should include a summary of how you solved the problem, so that readers can learn the general principle and apply it to other examples, rather than just copy and pasting the solution. – IMSoP Sep 09 '20 at 12:10
  • I agree. I added a brief explanation about how this regex works – Sumak Sep 09 '20 at 12:16
0

Firstly, you have a missing set of brackets around the year part, so the | operator will split the whole pattern, like this:

  • ^(0[1-9]|10|11|12)/1[9]
  • or
  • 2[0-9]{2}$

Secondly, your year pattern is asking for a 2 followed by 2 digits (the {2} modifier) so will match 200, 299, etc. You actually want a single digit in the range 2 to 9 followed by a single digit 0 to 9: [2-9][0-9]

Finally, there's no need to put square brackets around the 9; it doesn't matter, but it makes it harder to read for no purpose.

Putting those fixes together:

^(0[1-9]|10|11|12)/(19|[2-9][0-9])$
IMSoP
  • 89,526
  • 13
  • 117
  • 169