Only allow negative sign as first character in "number" type input box

Viewed 1301

Is there a way only allow a negative sign (or hyphen) for the first character in an input tag of type "number"? It has to be type "number" so that the correct keyboard appears on mobile. However, a user can still enter multiple negative signs before clicking "Submit". I have used .checkValidity(), which helps, but prevents entering a negative sign in the first place unless I type a number first. I can't validate with .value, since that returns a blank if it is invalid.

HTML

<input type="number" id="input">

JavaScript

var input = document.querySelector('#input');
var value;

input.oninput = function() { 
    if (input.checkValidity()) {
        value = input.value;
    }
    else{
        input.value = value;
    }
}

Any help is appreciated. Thanks!

4 Answers

Try:

<input type="number" id="input" oninput="this.value.match(/^-?\d*\.?\d*$/)||(this.value='');">

Use custom Regexp to test input. Only one hyphen at the begining will be allowed.

/^[-0-9][0-9]+$/.test(input)

So the code block may be

input.oninput = function() { 
  if (/^[-0-9][0-9]+$/.test(input.value)) {
      value = input.value;
  }
  else{
      input.value = value;
  }
}

I have not tested but I think that would help.

You can use a regex that matches nothing but digits then check for matches and set the input value accordingly, on input.

const el = document.querySelector('#myInput');
el.value = '-';

el.addEventListener('input', e => {
  const m = e.target.value.match(/\d+/g);
  el.value = m === null ? '-' : `-${m}`;
});
<input id="myInput" type="text" />

The pattern HTML attribute is pretty well supported these days, so you might use it for this validation.

Try to play with the form in the snippet below -- if the value is not a number, a tooltip appears and the form won't submit. No JS.

<form action="#">
  <input type="number" id="input" pattern="^-?\d+$">
  <input type="submit">
</form>

To validate while user is inputting, you'll need JS:

input:invalid {background:#f009}
<form action="#">
  <input type="number" id="input" pattern="^-?\d+$" oninput="this.checkValidity()">
  <input type="submit">
</form>

Related