1

I need a regular expression which accepts dates like this: 12/12/2018 , uu/12/2018, uu/uu/2018, uu/uu/uu

but doesn't accept this kind of dates: 12/uu/2018, 12/uu/uu, 12/12/uu etc.

I am using this RegEx from Ofir Luzon:

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

posted here

aggicd
  • 727
  • 6
  • 28
  • probably using a normal date regex with 2 or statements handling the other cases will work just fine. (dateRegEx | uuDateRegEx | uuuuDateRegEx). – Shawn Tabrizi Jan 16 '18 at 10:42
  • @ShawnTabrizi but this will validate also dates like `12/12/uu` which is not acceptable – aggicd Jan 16 '18 at 10:43
  • Not if you make your regex require the first two numbers to be uu for the last part to be uu aswell... literally 4 different statements which check for the specific conditions you require – Shawn Tabrizi Jan 16 '18 at 10:44
  • @ShawnTabrizi can you provide an example of your approach? – aggicd Jan 16 '18 at 10:48
  • something like [this](https://regex101.com/r/CjCA98/2). It gets more complicated once you start adding in the specific date regex you show above, but that is the idea. – Shawn Tabrizi Jan 16 '18 at 11:01
  • @ShawnTabrizi yeap now I got your approach, it should work as long as I manage to add my regex – aggicd Jan 16 '18 at 11:06
  • You should probably use variables for the sub-regex for day, month and year, so you don't have to repeat those parts. Also would make the entire thing much more readable. – tobias_k Jan 16 '18 at 11:44
  • It seems like that super-complicated regex you have there even validates leap years and stuff like this. Do you really really need this? And how should that even work if either day or month is `uu`? I'd suggest using a simpler regex, like the one by @ShawnTabrizi, and then validating the date afterwards using some library. – tobias_k Jan 16 '18 at 11:47
  • @tobias_k I need to validate leap years only in case that the date is fully known. If it contains unknown dates then a simple regex will work – aggicd Jan 16 '18 at 11:54

1 Answers1

1

Maybe this will do the trick:

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$|(uu\/([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])\/[0-9]{1,4})|(uu\/uu\/[0-9]{1,4})|(uu\/uu\/uu)

//removed unnecessary parentheses 
aggicd
  • 727
  • 6
  • 28
atroul
  • 219
  • 2
  • 9