Allow enter only numbers in text box with javascript for mobile devices

2

I have a function in JavaScript to fill out forms that allows me to only enter numbers in a text box.

The problem is that it only works on computers and not on mobile devices.

function validarNumero(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla==8) return true; 
    patron =/[0-9]/;
    te = String.fromCharCode(tecla); 
    return patron.test(te); 
 }

And in the HTML code part

<input type="text" id="txtNumero" maxlength="10" onkeypress="return validarNumero(event)">
    
asked by Popularfan 14.08.2018 в 10:27
source

3 answers

2

If you can not use HTML5 and CSS3 then maybe the most portable thing is to capture the events keyup and change to eliminate the numbers of the field of the form in the following way:

function limpiarNumero(obj) {
  /* El evento "change" sólo saltará si son diferentes */
  obj.value = obj.value.replace(/\D/g, '');
}
<input type="text" id="txtNumero"
  maxlength="10"
  onkeyup="limpiarNumero(this)"
  onchange="limpiarNumero(this)"
/>

The reason is the complexity of keystrokes that you must filter to maintain compatibility with everything (mobile devices, copy / paste, move with the cursor, select part of the text, etc.).

In the documentation you will see more information about the keyboard codes .

I personally would maintain a hybrid version that could make use of HTML5 capabilities if present.

I keep the HTML5 + CSS3 version in the change history.

    
answered by 14.08.2018 / 10:54
source
1

I propose 2 solutions.

Use:

<input type="number">

With this you get the numeric keypad on the mobile. This has pros and cons.

On the one hand you save validations and have a more protected data entry. On the other hand, you can not put a zero in front of '0898' for example, it would eliminate you 0. This is a problem if they are postal codes, telephone numbers, etc ...

Another solution is to use:

<input pattern="[0-9]{7,15}">

This is a validation by HTML5 and works in the same way as required , minlength , maxlength , etc.

The example above validates that it is a string of between 7 and 15 digits where there can only be characters between 0-9 (it works very well for a first validation of telephones)

This is just an example, you can use any regular expression that works for you.

I do not know how to improve your javascript code but you could keep this option for a computer and use one of these mobile options.

    
answered by 14.08.2018 в 10:55
1

You should use the type number of the input as long as you do not need to support devices older than those shown in the table caniuse .

<input type="number" />

UPDATE

Since you can not use HTML5, you could try this function:

function validarNumero(e){
    var charCode = (e.which) ? e.which : e.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
        return false;
    }
    return true;
}
    
answered by 14.08.2018 в 10:55