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?
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.
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.
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).
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}$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With