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>
You must be able 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 onblur event? I would like that when losing the focus, it checks if there are 5 digits, if there are, nothing happens, if there are not 5 digits, it shows a message (alert()) and puts the background of the field in red.
styles.css
.error{
background-color: red;
}
What happens is that you have to validate 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 numberI took your code, removed some extra stuff, and added the validation of
preventDefault()
Cheers
Using the DOM level 2 definition it
return
doesn't work as you expect. You should useEvent.preventDefault()
instead.Finally, the condition must be the opposite of the one you had raised:
You can only do it with html, create your input of type number. Something like this:
Here is something simpler. A greeting