Given a value I want to validate it to check if it is a valid year. My criteria is simple where the value should be an integer with 4
characters. I know this is
This works for 1900 to 2099:
/(?:(?:19|20)[0-9]{2})/
The "accepted" answer to this question is both incorrect and myopic.
It is incorrect in that it will match strings like 0001
, which is not a valid year.
It is myopic in that it will not match any values above 9999. Have we already forgotten the lessons of Y2K? Instead, use the regular expression:
^[1-9]\d{3,}$
If you need to match years in the past, in addition to years in the future, you could use this regular expression to match any positive integer:
^[1-9]\d*$
Even if you don't expect dates from the past, you may want to use this regular expression anyway, just in case someone invents a time machine and wants to take your software back with them.
Note: This regular expression will match all years, including those before the year 1, since they are typically represented with a BC designation instead of a negative integer. Of course, this convention could change over the next few millennia, so your best option is to match any integer—positive or negative—with the following regular expression:
^-?[1-9]\d*$
/^\d{4}$/ This will check if a string consists of only 4 numbers. In this scenario, to input a year 989, you can give 0989 instead.
You could convert your integer into a string. As the minus sign will not match the digits, you will have no negative years.
To test a year in a string which contains other words along with the year you can use the following regex: \b\d{4}\b
Building on @r92 answer, for years 1970-2019:
(19[789]\d|20[01]\d)