<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function validar(element)
{
// obtenemos el dataset con los valores minimos para ese campo
const min=parseInt(element.dataset.lengthmin);
if(element.value.length>=min)
{
// tiene los caracteres minimos
element.classList.remove("borderRed");
return true;
}else{
// no tiene los caracteres minimos
element.classList.add("borderRed");
return false;
}
}
/**
* Function que valida que todos los valores del formulario tengan el tamaño
* minimo indicado.
* Se ejecuta antes de enviar el formulario.
*/
function validarFormulario(formulario)
{
let result=true;
const input=formulario.querySelectorAll("input[type=text]");
// recorremos todos los input para ver si algun input no cumple con los caracteres minimos
for (i of input) {
if (validar(i)==false) {
result=false;
}
}
return result;
}
</script>
<style>
input[type=submit] {display:block;}
form span {display:inline-block;width:100px;}
form div {margin:5px;}
.borderGrey {border:2px solid Grey;}
.borderRed {border-color: Red;}
</style>
</head>
<body>
<form action="pagina.php" method="post" onsubmit="return validarFormulario(this);" name="MiFormulario">
<div>
<span>Nombre:</span>
<input type="text" name="nombre" onkeyup="validar(this);" data-lengthMin="1" class="borderGrey">
</div>
<div>
<span>Apellidos:</span>
<input type="text" name="apellidos" onkeyup=validar(this); data-lengthMin="1" maxlength="4" class="borderGrey">
</div>
<div>
<span>Código:</span>
<input type="text" name="codigo" onkeyup=validar(this); data-lengthMin="4" maxlength="4" class="borderGrey"> (4 caracteres)
</div>
<input type="submit" value="Enviar">
</form>
</body>
</html>
No hay comentarios
Modificamos el color utilizando classList