Validation field input text - You must only accept numbers - Javascript

2

A field input in a form:

<td align=right>Cod.Postal:</td><td align=left><input type="text" name="codigo" id="idcodigo" maxlength="5"></td>

It should be possible to write only numbers (0-9).

    window.addEventListener("load", function() {
    miformulario.codigo.addEventListener("keypress", function(){ 
        return soloNumeros(event);
        }, false);
    });

    //Solo permite introducir números.
    function soloNumeros(e){
    var key = window.event ? e.which : e.keyCode;
    if (key < 48 || key > 57) {
        //Usando la definición del DOM level 2, "return" NO funciona.
        e.preventDefault();
    }
}

ValidarCP function:

//Validar el CP.
function validarCP(){
    //Eliminamos la clase error asignada al elemento CP.
    document.getElementById("idcodigo").className="";
    var valor = document.getElementById("idcodigo").value;
    var patron = /^\d{5}$/;
    if (patron.test(document.getElementById("idcodigo").value) && (!isNaN(valor))){
        document.getElementById("idcodigo").className="correcto";   
        return true;
    }else{
        //Situamos el foco en el campo idcodigo y le asignamos la clase error.
        alert("El código debe tener al menos 5 digitos.\n");
        document.getElementById("idcodigo").focus();
        document.getElementById("idcodigo").className="error";  
        return false;
    }
}

How would you assign this ValidarCP function to the "code" field? With the event onblur? I would like that if you lose the focus, check if there are 5 digits, if there are nothing, if there are not 5 digits, that it shows a message (alert ()) and that it puts the background of the field in red.

styles.css

.error{
    background-color: red;
}
    
asked by omaza1990 16.05.2017 в 16:04
source

3 answers

2

Using the definition of the DOM level 2 the return does not work as expected. You must use Event.preventDefault() instead.

Finally, the condition must be the opposite of the one you had raised:

window.addEventListener("load", function() {
  miformulario.codigo.addEventListener("keypress", soloNumeros, false);
});

//Solo permite introducir numeros.
function soloNumeros(e){
  var key = window.event ? e.which : e.keyCode;
  if (key < 48 || key > 57) {
    e.preventDefault();
  }
}
<form name="miformulario">
  <td align=right>Cod.Postal:</td><td align=left><input type="text" name="codigo" id="idcodigo" maxlength="5"></td>
</form>
    
answered by 16.05.2017 / 16:26
source
3

What happens is that you have to do the validation by the input in JavaScript, even if you return a false, it does not know what to do, you have to add the e.preventDefault() so that now it does not allow writing characters that are not of type number

miFormulario = document.querySelector('#miFormulario');
miFormulario.codigo.addEventListener('keypress', function (e){
	if (!soloNumeros(event)){
  	e.preventDefault();
  }
})

//Solo permite introducir numeros.
function soloNumeros(e){
    var key = e.charCode;
    console.log(key);
    return key >= 48 && key <= 57;
}
<form name='miFormulario' id='miFormulario'>
<input type="text" name="codigo" id="idcodigo" maxlength="5">
</form>

I took your code, removed some other things, and added the validation of preventDefault()

Greetings

    
answered by 16.05.2017 в 16:25
1

You can do it only with html, create your input of type number. Something like this:

  

input type="number" name="code" id="idcode" min="0" max="9"

    
answered by 16.05.2017 в 16:29