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;
}