DebugPointer
Published on

Regex for age validation

Regex for age validation

Age of a person validation using regex is achieved in this case to check if the age is above 18 years or above (until a maximum of 99 years). In this article let's understand how we can create a regex for age of a person and how regex can be matched for age.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Conditions to match age limit

The age of the person has to be-

  • More than 18 years
  • Less than 100 years

Regex for checking if age is greater than 18 years

Regular Expression-

/^(1[89]|[2-9]\d)$/gm

Test string examples for the above regex-

Input StringMatch Output
10does not match
18matches
120does not match
67matches

Here is a detailed explanation of the above regex-

/^(1[89]|[2-9]\d)$/gm

^ asserts position at start of a line
1st Capturing Group (1[89]|[2-9]\d)
1st Alternative 1[89]
1 matches the character 1 with index 4910 (3116 or 618) literally (case sensitive)
Match a single character present in the list below [89]
89 matches a single character in the list 89 (case sensitive)
2nd Alternative [2-9]\d
Match a single character present in the list below [2-9]
2-9 matches a single character in the range between 2 (index 50) and 9 (index 57) (case sensitive)
\d matches a digit (equivalent to [0-9])
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Hope this article was useful to check the age of a person if its greater than 18 years old.