skip to Main Content

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


  1. You could use 1 pattern for the first 2 calls to replace:

    [^0-9.n-]+|^-(?:1.0*[1-9]|[2-9]|1d+).*|(?!^)-
    

    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 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 string

    See 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]|1d+).*|(?!^)-/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]|1d+).*|(?!^)-|(?<!^[^n.]*)./g, '');
    }
    
    const inp = document.getElementById("mynumber");
    
    if (inp) {
      inp.addEventListener("input", handleInput);
    }
    <input type="text" id="mynumber" />
    Login or Signup to reply.
  2. 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:

    let thisValue = document.getElementById("mynumber");
    if( thisValue < -1){
        // Good
    }else{
        // Bad - do something here
    }
    

    (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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search