Function in onpaste

Asked

Viewed 44 times

1

I have this input where I own a function, just to accept numbers by typing it works, however I would like to put this function in the onpaste also, if I do putting onpaste="return SomenteNumeros(event)", does not work. Does not recognize, it lets pass letters, dots, commas , etc. It would be necessary to put in the onpaste, to validate this information.

  function SomenteNumeros(event) {
        if (event.keyCode < 48 || event.keyCode > 57)
            return false;
    }
<input  class="form-control" maxlength="8" placeholder="Somente números." OnKeyPress="return SomenteNumeros(event)">
                        

  • The way it is already blocks collage of non-numeric characters.

2 answers

3

Use oninput in place of onkeypress sending the element as a parameter to the function through the this:

oninput="SomenteNumeros(this)"

The advantage of oninput is that it detects any changes in the field, either via mouse or keyboard, while the onkeypress only detects the keyboard.

And in the function make a .replace with a regular expression eliminating anything that is not a number:

.replace(/[^\d]/g, '');

The expression /[^\d]/g selects everything that is not number (\d). This way, even pasting, via mouse or keyboard, will eliminate any non-numeric character.

Behold:

function SomenteNumeros(el) {
  el.value = el.value.replace(/[^\d]/g, '');
}
<input type="text" class="form-control" maxlength="8" placeholder="Somente números." oninput="SomenteNumeros(this)">

2


Or in the onkeyup (even if you stick it will treat):

//Permite Ponto
function somenteNumeros(num) {
  var er = /[^0-9.]/;
  er.lastIndex = 0;
  var campo = num;
  if (er.test(campo.value)) {
    campo.value = "";
  }
}


//Permite virgula
function somenteNumeros2(num) {
  var er = /[^0-9,]/;
  er.lastIndex = 0;
  var campo = num;
  if (er.test(campo.value)) {
    campo.value = "";
  }
}
<input type="text" class="form-control" id="tes" onkeyup="somenteNumeros(this);">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.