I'm trying to write a regular expression to validate a form field that is allowed to have a decimal data type, up to 8 digits long, that is greater than 0 but less than 100. The following seems to be close, although it permits zero and that is where I'm stuck. What should be modified to prevent zero from matching?
^([0-9]{1,2})(\.[0-9]{0,8})?$
Asked
Active
Viewed 2,590 times
1

knot22
- 2,648
- 5
- 31
- 51
-
3This shouldn't be a pattern match, it's a value match. If the input is a valid number, convert it to a number and use < and > to see if it's in range. – Bill the Lizard Jun 19 '18 at 15:13
-
The `{0,8}` is to allow up to 8 decimal places. – knot22 Jun 19 '18 at 15:14
-
It fails with `000010.1`, too. – Daniel W. Jun 19 '18 at 15:15
-
1The purpose of regular expressions is to validate the format, not the value. Use a simple `regex` to validate the format (the one you already have, without trying to check the range) then use the regular comparison operators to check if the value (already validated as number by the `regex`) belongs to a certain range. This way the intention is clear and the code is simple and easy to understand. – axiac Jun 19 '18 at 15:19
-
@axiac that sounds like a good approach. The regex is being put in the HTML pattern attribute though. Can normal comparison operators be used with that? – knot22 Jun 19 '18 at 15:23
-
1There is no bulletproof client side data validation. This task is done serverside. – Daniel W. Jun 19 '18 at 15:26
-
If your HTML element is like `` (add `value`, `name` and other attributes you need) then you don't even need a validation `regex`. – axiac Jun 19 '18 at 15:32
-
1Evaluate decimal numbers as decimal numbers, not as patterns. Your question doesn't mention anything about an "HTML pattern attribute". At this point it only asks how to do something the wrong way. – ghoti Jun 19 '18 at 15:40
-
Try `^(?!0*$)\d\d?(?:\.\d{1,8})?$`. I will mark this as a duplicate. – revo Jun 19 '18 at 16:58
1 Answers
0
Use a positive look behind
^([1-9]?(?<=[1-9])[0-9]?)(\.[0-9]{0,8})?$
learn more here https://www.regular-expressions.info/lookaround.html and use this to play around with https://regex101.com/

Stefan
- 352
- 3
- 15