1

I need to make a regular expression to validate age between 17-120 include (17 and 120)

I tried this

^(100|[1-9][7-9][0-9]?)$

I know it is not good but I can not understand how to do it

I need it of age filed inside my form with pattern attribute

Only numbers allow

rsjaffe
  • 5,600
  • 7
  • 27
  • 39

2 Answers2

5

You should put all the possible combinations in the alternation list:

^(?:1[01][0-9]|120|1[7-9]|[2-9][0-9])$

Demo: https://regex101.com/r/6SzInz/1

Basically you need one pattern for each of the boundary conditions:

  • 1[7-9] covers numbers between 17 and 19
  • [2-9][0-9] covers numbers between 20 and 99
  • 1[01][0-9] covers numbers between 100 and 119
  • and 120 covers the number... 120
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • What if it was between 17 and 1000000? Would you really put all possible combinations?? – Anis R. Jan 15 '19 at 23:30
  • Yes, it's also very easy: `^(?:1[7-9]|[2-9][0-9]|[1-9][0-9]{2,5}|1000000)$` (demo: https://regex101.com/r/6SzInz/2 ). No matter how large the range is, you just need a few patterns to cover the boundary conditions, and everything else in between can be covered with just one pattern. – blhsing Jan 15 '19 at 23:36
  • Regex is sometimes required in validation for certain form-based apps, where you can't use mathematical expressions to specify ranges. – blhsing Jan 15 '19 at 23:37
0

You cannot achieve exactly this using regular expressions. With a regular expression, you can check if a string follows a certain pattern, i.e. "what the string looks like" if you want.

For example, ^[0-9]{2,3}$ is a regular expression for checking that the input consists of only two or three digits/numbers.

For the "between 17 and 120" part, I guess you need to use a JS if statement, similar to this:

if(age <= 120 && age >= 17) {
  //accept, and do your stuff
}
else {
  //show some validation error
}

Edit: Of course you can do as @blhsing said for this specific case, but in a more general sense, it can be pretty tedious in many cases.

Anis R.
  • 6,656
  • 2
  • 15
  • 37