-3

Date Regex with special character as optional pre element

I need a date regex for YYYY-MM-DD, plus the following four case:

1978-12-20
>1978-12-20
>=1978-12-20
<1978-12-20
<=1978-12-20

How can I allow those 5 scenarios?

Philipp M
  • 3,306
  • 5
  • 36
  • 90
  • 2
    I'm voting to close this question as off-topic because it shows no attempt at writing code to implement the required logic. – RobG Dec 09 '19 at 22:20

1 Answers1

1

Imho, a regex is not the best tool for you, but if you still want to use a regex... a basic one, then you can use a regex like this:

^(?:>=?|<=?)?\d{4}-\d{2}-\d{2}$

Working demo

Regex to match dates are kinda ugly. You can validate easily patterns, but dates have logic... for instance, not all months have 30 days, years are only 12 (should you count 01, 02, 03 or 1, 2, 3...).

Bear in mind that using above regex you will have invalid dates. So, you might want to capture the date string to ensure that it is valid first, and then apply this pattern to check if it is correct.

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • This is matching `=1234-12-12` but not wanted. – Toto Dec 09 '19 at 13:45
  • @PhilippM, I've updated the answer with more details, however in your question you didn't put almost any information. So, I came up with this basic regex. – Federico Piazza Dec 09 '19 at 13:45
  • @Toto, nice catch... thanks. Just fixed it. – Federico Piazza Dec 09 '19 at 13:47
  • I'm actually using https://github.com/hapijs/joi/blob/master/API.md#date but want to allow those additional four scenarios – Philipp M Dec 09 '19 at 13:47
  • @PhilippM, let me know if it works fine – Federico Piazza Dec 09 '19 at 14:07
  • What do you think about this regex? ^(?:>=?|<=?)?([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])) – Philipp M Dec 09 '19 at 14:08
  • @PhilippM that's what I mean by "ugly". Your regex is correct... by imho hard to read, but if you are ok with it... go for it. In my personal case, I would go with my regex and validate that the date is correct with a regular date object. – Federico Piazza Dec 09 '19 at 14:39
  • Don't validate dates using a regular expression, it's way more complex than it needs to be. To test per the OP, `/^(>=?|<=?)?\d{4}-\d{2}-\d{2}$/` is sufficient. Then [validate the date](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+validate+a+date) separately. – RobG Dec 09 '19 at 22:35