Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate the range 1-99 using a regex?

I need to validate some user input, to ensure a number entered is in the range of 1-99 inclusive. These must be whole (Integer) values

Preceeding 0 is permitted, but optional

Valid values

  1. 1
  2. 01
  3. 10
  4. 99
  5. 09

Invalid values

  1. 0
  2. 007
  3. 100
  4. 10.5
  5. 010

So far I have the following regex that I've worked out : ^0?([1-9][0-9])$

This allows an optional 0 at the beginning, but isn't 100% correct as 1 is not deemed as valid

Any improvements/suggestions?

like image 836
Jimmy Avatar asked Oct 25 '10 08:10

Jimmy


People also ask

How do you do a range in regex?

\d for single or multiple digit numbers It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range. [1-9][0-9] will match double digit number from 10 to 99.

How do you validate a form in regex?

You can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only if the user input matches the pattern.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

Off the top of my head (not validated)

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

like image 185
developmentalinsanity Avatar answered Oct 31 '22 18:10

developmentalinsanity


Here you go:

^(\d?[1-9]|[1-9]0)$

Meaning that you allow either of

  1. 1 to 9 or 01 to 09, 11 to 19, 21 to 29, ..., 91 to 99
  2. 10, 20, ..., 90
like image 39
Alin Purcaru Avatar answered Oct 31 '22 18:10

Alin Purcaru