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');" />
You could use 1 pattern for the first 2 calls to replace:
[^0-9.\n-]+|^-(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-
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]|1\d+)
Match either 1.
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.
function handleInput() {
this.value = this.value.replace(/[^0-9.\n-]+|^-0*(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-/g, '').replace(/(\..*)\./g, '$1');
}
const inp = document.getElementById("mynumber");
if (inp) {
inp.addEventListener("input", handleInput);
}
<input type="text" id="mynumber" />
If a lookbehind assertion is supported in your JavaScript environment, you can use a single replace:
function handleInput() {
this.value = this.value.replace(/[^0-9.\n-]+|^-0*(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-|(?<!^[^\n.]*)\./g, '');
}
const inp = document.getElementById("mynumber");
if (inp) {
inp.addEventListener("input", handleInput);
}
<input type="text" id="mynumber" />