i try to catch an input of a field via javascript.
i need to get max 3 numbers and one dot.
i tried this regex: [^\d{0,3}.{0,1}\d{0,3}]
but it isn't quite working, i can't really get how to fetch the numeric values globaly so it is really max 3 numbers.
333 //ok
333 //ok
33.1 //ok
3.33 //ok
3.3. //not ok
3.333 //not ok
3333. //not ok
3.. //not ok
. //not ok
Hope someone can give me a hint here.
For on-submit (final) validation, you can use
^(?=.{3,4}$)\d+(?:\.\d+)?$
See the regex demo. It matches
^ - start of string(?=.{3,4}$) - this requires the string to have three or four chars only\d+(?:\.\d+)? - one or more digits, and then an optional occurrence of a . and one or more digits. As \d, \. and \d are obligatory to match at least once, the min limit as 3 is justified and since only one dot can be matched, either of \d+ can match one or two digits, but only three all in all$ - end of string.For live input text validation, you can use
^(?:\d{1,3}|\d(?:\d?\.\d?|\.\d{2}))$
See the regex demo. Details:
^ - start of string(?: - start of a group:
\d{1,3} - one, two or three digits| - or
\d - a digit(?:\d?\.\d?|\.\d{2}) - a non-capturing group matching either
\d?\.\d? - an optional digit, a . and then an optional digit| - or\.\d{2} - . and then two digits) - end of the group$ - end of string.I am very bad in regex but came up with something like this below. Probably there is a much more elegant way but....
^\d{0,3}$|^\d{2}[.]\d{1}$|^\d{1}[.]\d{1,2}$
Works for MAX 3 numbers so 3 and 33 is also ok
You might also match all 3 variations in a non capture group:
^(?:\d{3}|\d\.\d\d|\d\d\.\d)$
Or first match a single digit followed by 2 variations of an optional dot and 2 digits or a single digit, optional dot and a single digit:
^\d(?:\.?\d\d|\d\.?\d)$