0

I have the following regex for validating a date of format mm/yyyy. For month should be greater than current and year should be current or till 2018.

^((0[8-9]|(1[0-2])))\/((16))|((0[1-9])|(1[0-2]))\/((2016)|(2017)|(2018))$

In case of current year month should be greater than current month. but for years greater than current, it should validate all months. With this current regex, it validates 08/2016 too. However, I want it to validate 09/2016 onwards. Whats wrong with this regex?

P.S For some reasons, I have to validate dates with this regex. So kindly don't suggest to validate dates with built-in date functions

seairth
  • 1,966
  • 15
  • 22
  • 2
    dont do this special case with regex. reges are great for format-validation, not for any kind of dynamic validation. – ZPiDER Aug 24 '16 at 18:41
  • You have to dynamically generate this regex. It's fairly easy. Why is there an alternation based on the last 2 digits of the year? The two year parts can be combined into a single alternation, prepending `(?:20)?`, with sub alternations for the current month. –  Aug 24 '16 at 18:54
  • There is hardly such a reason to validate a *date* with regex. Especially in C# where you have `DateTime` class that does most of the work for you. Please explain. – Wiktor Stribiżew Aug 24 '16 at 18:54
  • Anyway, you don't need all those capture groups, and the anchors `^$` are misplaced. And really, it's better to split on `/` then do the analysis for validation. –  Aug 24 '16 at 18:58
  • Your question already answered in generic way http://stackoverflow.com/questions/1377926/regular-expression-numeric-range ... – Alexei Levenkov Aug 24 '16 at 19:00
  • Here is an example for _Month is 7, Year is 16_ `^(?:(?:0[8-9]|1[0-2])/(?:20)?16|(?:0[1-9]|1[0-2])/(?:20)?1[7-9])$`. You can force it into 4 digit year with this `^(?:(?:0[8-9]|1[0-2])/2016|(?:0[1-9]|1[0-2])/201[7-9])$` Only a portion of the regex is dynamic. In fact, you can _pre-create_ the variable month part into an array of 12 strings, pick one based on the month, and insert it into the regex. The dynamic year part is straight forward to generate. –  Aug 24 '16 at 19:28
  • Here is a sample of the premade10 months regex part's you'd need 1) "`(?:0[2-9]|1[0-2])`"; - 2) "`(?:0[3-9]|1[0-2])`"; skip to - 8) "`(?:0[9]|1[0-2])`"; - 9) "`(?:1[0-2])`"; - 10) "`(?:1[1-2])`"; - 11) "`(?:1[2])`" –  Aug 24 '16 at 19:38

1 Answers1

0
^((09|10|11|12]))\/((2016))|((0[1-9])|(1[0-2]))\/((2017)|(20‌​18))$

what was wrong?

  1. you had 2016 in the right part
  2. you allowed 08 in the left part
  3. you only checked "16" in the left part (instead of "2016")

btw: i hope for you that you dont need to change this regex at midnight of every 1st! ;)

ZPiDER
  • 4,264
  • 1
  • 17
  • 17