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 not the best solution as it will not allow years before 1000
and will allow years such as 5000
. This criteria is adequate for my current scenario.
What I came up with is
\d{4}$
While this works it also allows negative values.
How do I ensure that only positive integers are allowed?
You need to add a start anchor ^
as:
^\d{4}$
Your regex \d{4}$
will match strings that end with 4 digits. So input like -1234
will be accepted.
By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.