Regular expression for dates matching for each stage of a valid date record

I am trying to collect a regular expression that matches any part of a valid date, while the part starts from the front. The actual date is defined as DD / MM / YYYY from 1900 <= YYYY <2100. I don’t care about leap years, days in the months are different depending on the month, etc.

The goal is to provide validation feedback to users as they are entered, but only when they are on the wrong track. I believe this improves user experience.

So for example:

'1' matches (as eg 12/12/1999 is a valid date) '4' does not match '04' matches '12/12/' matches 

This is where I got it:

 ^(([0123]\d?)|([0123]\d\/[01]?)|([0123]\d\/[01]\d\/?)|([0123]\d\/[01]\d\/(1|2|19\d{0,2}|20\d{0,2})))$ 

Any simpler ways to do this with regex?

refiddle

0
javascript regex validation
source share
1 answer

Yes there is. The basic approach is that if there are parts A, B and C at the input, write:

 /^A(B(C)?)?$/ 

etc. for any number of segments. This makes the whole part, starting with B extra, so it will fit on its own. This makes C an option, so AB will match. And of course, ABC will match.

The trap here processes the eyelids, which requires some special processing. In general, the solution looks something like this:

 /^[0-3](\d(\/([01](\d(\/((1(9(\d(\d)?)?)|((2(0(\d(\d)?)?)?))?)?)?)?)?)?)?)?$/ 
+1
source share

All Articles