Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: validate european date format with multiple separators

Tags:

regex

I want to validate european date formats like "10.02.2012" or "10-02-2012". Therefore I created the following regex:

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

Unfortunately I always get the message not valid, even when the date has the right format.

When I replace the "(.|-)" with "." for validating only dates separated with a dot it works. So i guess the problem must be the "(.|-)" Any ideas?

like image 334
flyte321 Avatar asked Sep 18 '12 08:09

flyte321


People also ask

How do you format a date in regex?

The regex matches on a date with the YYYY/MM/DD format and a "Date of birth:" or "Birthday:" prefix (Year min: 1900, Year max: 2020). For example: Date of birth: 1900/12/01.

Which of the following is the correct regex to match the date format dd mm yyyy?

Regular Expression for Basic Format Dates (YYYYMMDD) ISO 8601 allows for date representations without the hyphens separating the parts of the date. For example 14 June 2021 can be written as 2021-06-14 in the extended human-readable format but also as 20210614 in the basic format.

How do you add expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

Note that the answers provided so far using the \d character class will allow dates such as 00.00.0000 or 99.99.9999 to pass through. If you want to catch this, you need to use a more specific regex. The one below would allow valid dates between 01.01.1900 and 31.12.2099

^([1-9]|0[1-9]|[12][0-9]|3[01])[-\.]([1-9]|0[1-9]|1[012])[-\.](19|20)\d\d$

If you want to allow any year from 0000 to 9999, then you could change it to

^([1-9]|0[1-9]|[12][0-9]|3[01])[-\.]([1-9]|0[1-9]|1[012])[-\.]\d{4}$
like image 117
Jens Wegar Avatar answered Sep 18 '22 22:09

Jens Wegar