I want a number, a minimum of -1, and only a negative being inputed at the start.
This is what I have so far. The -1 minimum does not work. The single decimal point works great. The single negative sign works great. BUT I cannot force the negative to only appear at the start.
How can I get the negative only at the start if required?
How can I get the minimum of -1 working?
<input type="text" id="mynumber" min="-1"
oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(..*)./g, '$1').replace(/(--*)-/g, '$1');" />
2
Answers
You could use 1 pattern for the first 2 calls to replace:
The pattern matches:
[^0-9.n-]
Match 1+ chars not being any listed in the character class|
Or^-0*
Match-
at the start of the string followed by optional zeroes(?:1.0*[1-9]|[2-9]|1d+)
Match either1.
followed by optional zeroes and a digit 1-9, or match a digit 2-9 or match a number greater than 10.*
Match the rest of the line|
Or(?!^)-
Match a-
not at the start of the stringSee a regex demo.
Keep the last call to remove the second occurrence of the dot.
If a lookbehind assertion is supported in your JavaScript environment, you can use a single replace:
There may be good reasons for doing things the way that you ar trying, but I would let JS do the heavy-lifting for you, by something like:
(I would also flesh it out a little to cover non-numeric input possibilities, but then again I wouldn’t use a ‘number’ input type in the first place!