Search code examples
regexvalidationdaterepeatregex-greedy

repeating dd/mm/yyyy regex with separator


I'm working on client validation and in some cases my users are allowed to choose a date range or several dates at the same times with a date picker.

I found this regex to valid simple date :

Date regex 

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

This one allows many format :

dd/mm/yyyy

dd-mm-yyyy

dd.mm.yyyy

In the first case (date range), I use ' - ' as separator and I want to check the selected range with a regex :

01/02/2018 - 02/03/2018

I worked around and I am able to do this with a simplier regex :

^((\d{2})(?:\ \-\ |)){2}$

on this string

02 - 03

When I replace the first part (\d{2}) with my date regex and test the showed date range (01/02/2018 - 02/03/2018), the regex doesn't match.

In the second case(several dates selected), I'm using ',' as separator and I'm looking for a greedy quantifier solution.

Do you have any idea ?

Thanks


Solution

  • Here is your regex to select range with seperator comma or minus

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

    It works in so many cases as follows

    INPUT

    # dd/mm/yyyy - dd/mm/yyyy   01/02/2018 - 02/03/2018   01/02/2018 , 02/03/2018
    
    # dd-mm-yyyy - dd-mm-yyyy   01-02-2018 - 02-03-2018   01-02-2018 , 02-03-2018
    
    # dd.mm.yyyy - dd.mm.yyyy   01.02.2018 - 02.03.2018   01.02.2018 , 02.03.2018
    

    OUTPUT

    # 01/02/2018 - 02/03/2018   01/02/2018 , 02/03/2018
    
    # 01-02-2018 - 02-03-2018   01-02-2018 , 02-03-2018
    
    # 01.02.2018 - 02.03.2018   01.02.2018 , 02.03.2018