Validate input to only receive numbers with jquery?

Asked

Viewed 40,895 times

5

I need this input to receive only numbers:

<input class="form-control input-sm " placeholder="número" maxlength="4"  type="text"  ng-model="numero.nJogo" />

This I need to receive only values with this formatting (20.00)

<input class="form-control input-sm" placeholder="valor" maxlength="5" type="text"  ng-model="numero.valor" />
  • Didn’t see the preview before posting?

  • You can, as a suggestion, change the type of your input to number and let the browser validate it for you.

2 answers

16


This script accepts only numbers and "." :

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

Just add the onkeyup event to your input, this way:

<input class="form-control input-sm" onkeyup="somenteNumeros(this);" maxlength="5" type="text"  ng-model="numero.valor" />
  • was perfect, now I needed to format the other field, I thank!

  • I know you’re 3 years old, but which server is er.lastIndex = 0? @Bia

-3

$(input).keydown((event): boolean => {
   return ('0123456789'.search(event.key) > 0);
});

Browser other questions tagged

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