Regular expression for dates without separator

3

I have to know if a sequence of 8 numbers is a valid date in the format dd / mm / yyyy. The closest I came to was using this expression:

/^[0-3]{1}\d{1}[0-1]{1}[0-9]{1}[1-2]{1}\d{3}$/gm;

But it is returning true for sequences that are not valid dates, for example:

39091991 (39/09/1991)
10181991 (10/18/1991)

I would also like the year to have a limit, 1990 - 2020 .

I'm not much with regular expressions, so if anyone can help me.

    
asked by anonymous 17.03.2015 / 13:15

2 answers

4

Try this out

(0[1-9]|[1-2][0-9]|3[0-1])(0[1-9]|1[0-2])(199[0-9]|200[0-9]|201[0-9]|2020)

Being

Dias
(0[1-9]|[1-2][0-9]|3[0-1])

Mes
(0[1-9]|1[0-2])

Ano
(199[0-9]|200[0-9]|201[0-9]|2020)

Only problem is that it does not valid February (30.02.2000) for example is valid.

You can validate dates with this exp, but there is no year limitation:

(?:(?:(?:[01][1-9]|2[1-8])(?:0[1-9]|1[0-2])|(?:29|30)(?:0[13-9]|1[0-2])|31(?:0[13578]|1[02]))[1-9]\d{3}|2902(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00))
    
17.03.2015 / 13:43
4

Although @AdirKuhn has already provided an acceptable solution to the AP. After seeing it, I went looking for something more powerful, which could at least validate months of 30 and 31 days, because I knew that this was possible, even though I knew it was laborious.

So I found this answer in SOen , which went beyond my expectations, since it even validates dates for leap years (in the case on the 29th of February).

Then after some adaptations the Portuguese language (I removed the 01/Feb/2015 option, only accepting months in numbers: 01/02/2015 ), I share this powerful regular expression to validate dates:

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2)(?:(?:(?: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]))(?:(?:1[6-9]|[2-9]\d)?\d{2})$

The expression flowchart for better understanding:

Online sample in the tool used for debugging and generating the regular expression flowchart (Debuggex)

    
01.06.2015 / 16:15