-1

I have an input of type "text" where I want the user to be allowed to write inside just integers from -99 to 99.
The code so far is the following:

<input type="text" pattern="-?[0-9]{,2}" oninput="this.value=this.value.replace(/[^0-9\-]/g,'');">

The pattern returns valid=true even if the user just writes the minus sign (-) and this is not correct.
About the oninput, when the user writes a 3-digit number, the number remains in the field. The wanted behavior is to remove the third digit from the number.

Any ideas what to add to the pattern and the oninput in order to have correct results?


I have managed to do what I really wanted with a bit of JQuery.
Now the user can write ONLY numbers and the validity works as expected.
Here is the link: https://jsfiddle.net/panos78/2ctaonwL/
in case someone wants to see it how it works.

Panos
  • 89
  • 1
  • 9
  • The `pattern` attribute regex is a *final* input validation. You can enter whatever symbols in the input field. `.replace(/[^0-9\-]/g,'')` does not remove `-`s. So, this is fine. – Wiktor Stribiżew Jun 01 '22 at 08:06
  • 8
    Why not ``? Why do you try to make the UI actively worse? – VLAZ Jun 01 '22 at 08:07
  • @VLAZ I don't like the arrows on the right – Panos Jun 01 '22 at 10:06
  • @WiktorStribiżew You are correct. The pattern regex checks the final input but if I just put a minus sign (-), the input is consider valid and it shouldn't. That's why I say that I miss sth. – Panos Jun 01 '22 at 10:09
  • Good UX is not about what *you* like. It's about what is convenient and standard for users. A numeric field is *very* well-known and understood. Mobile devices will give you a numeric keyboard to fill it in and accessibility tools can also use this information. A text field with a regex for numeric values will bring up the full keyboard on mobile devices and make it harder for all users (even non-mobile) to type in a number only. Furthermore, validation is handled automatically with a useful message, as opposed to a random unknowable failure when a regex check fails. – VLAZ Jun 01 '22 at 10:09
  • @VLAZ If this is the case, how can I remove the arrows from the right side of the input with type number. – Panos Jun 01 '22 at 10:12
  • 1
    [Can I hide the HTML5 number input’s spin box?](https://stackoverflow.com/q/3790935) – VLAZ Jun 01 '22 at 10:13
  • I changed the input to number with min, max and step, as you have suggested and it accepts only positive integers. I will try to see how to figure it out with inputmode="numeric" and type="text" but still the regex is a problem – Panos Jun 01 '22 at 10:35
  • Just be aware that `number` limits the input to [valid floating point numbers](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-floating-point-number) and not to `-?[0-9]{,2}`. – JavaScript Jun 03 '22 at 11:41

0 Answers0