Make Your Regex Clearer - part 4

Putting all together, We can refactor the code:
The cryptic regular expression
 if (!value.match(/(0[1-9]|[12][0-9]|3[01])(?:-|\.)(0[1-9]|1[012])(?:-|\.)(19\d\d|20\d\d)/) {
   console.log('invalid date');
   ...
 }
with the following code:
The Clarified regular expression
 let reValidDate = new XRegExp(`
   # match a date. 
   # The date must be from 20 or 21 century.
   # format dd-mm-yyyy. seprator may be - or .
   (0[1-9]|[12][0-9]|3[01]) # group 1 - day 
   (?:-|\.)                 # seprator
   (0[1-9]|1[012])          # group 2 - month 
   (?:-|\.)                 # seprator
   (19\d\d|20\d\d)          # group 3 - year 
 `);;
 
 if (!reValidDate.test(value)) {  
   console.log('invalid date');
   ...
 } 

Summery

Regular expressions do not need to be cryptic. In this tutorial, we see how to clarify and simplify regular expressions.

First, With the help of RegExper, we have generate a nice diagram which help us understand what is the meaning of the regular expression.

Then, using those observations and XRegExp - a Javascript regex processor which support free-spacing mode - we have added comments about the regex inside it