regex date without the zero

1510 views regex
-3

I need to be able to allow dates in the format MM/DD/YYYY where the leading month and day can have a leading zero or not where appropriate

In other words: 01-09 or 1-9 are acceptable months 01-09 or 1-9 are acceptable days

I am very close with this:

/(0[1-9]|1[0-2])\/(0[1-9]|1[0-9]|2[0-9]|3(0|1))\/\d{4}/

With my limited knowledge I thought doing this would allow for a leading zero (or not)

/(0?[1-9]|1[0-2])\/(0[1-9]|1[0-9]|2[0-9]|3(0|1))\/\d{4}/

But that allows for dates such as 13/31/2008, for reasons I can't explain.

Question: I need a regular expression that allows all possible dates in the format MM/DD/YYYY where the month or day can contain leading zeros (or not) where both will pass.

Edit:

I am working with a 3rd party system that fails downstream if a users input is not a real date. The only tool I have against the input is Regex check. (For those that down voted my question)

answered question

Why are you over complicating it? /(\d{1,2}\/(\d{1,2})\/(\d{4})/, then do a separate check to make sure the day and month are ok (good luck with a regex that allows 2/29, but only on leap years)

I am inserting to another system that fails if it’s not a correct date (not worried about leap year). So 99/99/9999 won’t work.

1 Answer

2

You are very close, all you need is to anchor the regex to start and end (and make the zero in months optional too), like this:

^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3(0|1))\/\d{4}$

Now it won't accept 13/31/2008.

posted this

Have an answer?

JD

Please login first before posting an answer.