Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid entering double negative signs in an HTML numeric input

Tags:

html

input

My goal is to ensure that a classic <input type="number"> can only show a single minus sign at the beginning of the number (like... normal negative numbers?).

It feels quite dumb to ask this, but currently, in the following input I am able to input "--1", "-1-" or "1--", and in those cases, the value property of the native element just gives me an empty string. Is this somehow intended?

like image 593
Carlos Isidoro López Avatar asked Oct 16 '25 15:10

Carlos Isidoro López


1 Answers

try this :D!

       <input
        type="number"
        onKeyPress={event => {
          if (event?.key === "e" || event?.key === "+") {
            event.preventDefault();
          }
          if (event.target.value.length == 0 && event?.key === "-") {
            event.target.value = "";
          }
          if (event.target.value.length > 0 && event?.key === "-") {
            event.preventDefault();
          }
        }}
        onPaste={e => {
          const reg = "^[-]?[0-9]*\\.?[0-9]*$";
          const current = e.target.value;
          if (!current) {
            e.target.value = "";
          }
          if (
            !(current + e.clipboardData.getData("Text")).match(reg) &&
            e.clipboardData.getData("Text").match(reg)
          ) {
            e.target.value = "";
          }
          if (!e.clipboardData.getData("Text").match(reg)) {
            e.preventDefault();
          }
        }}
      />

The key press events allow for single minuses and avoid double minuses

Furthermore onPaste method will allow only valid numbers to be pasted

If the to be pasted clipboard is not a number then it will not be pasted.

If the current value + the clipboard is not a number only the clipboard will be pasted otherwise the current value + the to be pasted clipboard will be pasted.

like image 124
Bogdan Oleinikov Avatar answered Oct 18 '25 07:10

Bogdan Oleinikov