A regular expression for numbers from 0 to 100

I've been creating a web questionnaire (using the Forms Wizard module for mojoPortal CMS) that includes some questions where the answers were to be expressed as integer percentages. How to validate the responses? This was not quite as simple as I was hoping, as we need to use a RegularExpressionValidator and, as any fule kno, using regular expressions to solve a problem usually results in having two problems. So what's the expression? Of course regular expressions don't "understand" numbers, so it's not as simple as ^[0-100]$!

This expression seems to do the job without loopholes: ^([0-9]|[1-9][0-9]|100)$

If we want to permit decimals, then it gets more interesting. I'm no regexpert, but something like this should ensure we get either an integer from 0 to 100 or any decimal in between, with up to 2d.p. (also permitting 100.0 and 100.00!):

^100(\.[0]{1,2})?|([0-9]|[1-9][0-9])(\.[0-9]{1,2})?$

Spot any problems with these regular expressions...? Please comment and help me improve!

Comments

SAGAR CHAUHAN

re: A regular expression for numbers from 0 to 100

20 December 2018

thank you bro i really apriciate your telent thank for help

Nidhi Johari

re: A regular expression for numbers from 0 to 100

28 April 2020

Hi, 

This helped thank you. But I am trying to input percentage into an input field and i am not sure how to do that with regex. Could you maybe help with a solution?

re: A regular expression for numbers from 0 to 100

28 April 2020

You can validate input with the pattern attribute, something like this: <input type="text" pattern="([0-9]|[1-9][0-9]|100)" minlength="1" maxlength="3">

this

re: A regular expression for numbers from 0 to 100

08 October 2020

Wow

divya

re: A regular expression for numbers from 0 to 100

28 March 2022

hi, please tell me regex for number between 35 to 100

re: A regular expression for numbers from 0 to 100

28 March 2022

A regex for a number between 35 and 100...? Well this is simplistic, but easy to understand:

^(35|36|37|38|39|[4-9][0-9]|100)$

gfhdj

re: A regulartytur expression for numbers from 0 to 100

07 June 2022

dghfhjgj

Find out more