Inicio de la clase 9 #9

Open
maderademarco.sergio wants to merge 6 commits from maderademarco.sergio/clase-9-eventos:ejercicio-9 into main
3 changed files with 89 additions and 1 deletions
Showing only changes of commit d347427c7f - Show all commits

View File

@@ -51,3 +51,61 @@ botonCaptura.addEventListener('click', function() {
externo.addEventListener('click', function() {
console.log('capturing: externo');
}, true);
// Ejercicio 5 - Validación de formulario
const formulario = document.getElementById('formulario');
const nombreInput = document.getElementById('nombre');
const edadInput = document.getElementById('edad');
const mensajeInput = document.getElementById('mensaje');
const errorNombre = document.getElementById('errorNombre');
const errorEdad = document.getElementById('errorEdad');
const errorMensaje = document.getElementById('errorMensaje');
const formResultado = document.getElementById('formResultado');
function limpiarErrores() {
errorNombre.textContent = '';
errorEdad.textContent = '';
errorMensaje.textContent = '';
formResultado.textContent = '';
}
formulario.addEventListener('submit', function(event) {
event.preventDefault();
limpiarErrores();
let esValido = true;
const nombre = nombreInput.value.trim();
const edadValor = edadInput.value.trim();
const mensaje = mensajeInput.value.trim();
if (!nombre) {
errorNombre.textContent = 'El nombre no puede estar vacío.';
esValido = false;
}
if (!edadValor) {
errorEdad.textContent = 'La edad no puede estar vacía.';
esValido = false;
} else if (!/^[0-9]+$/.test(edadValor)) {
errorEdad.textContent = 'La edad debe ser un número entero positivo.';
esValido = false;
} else {
const edad = parseInt(edadValor, 10);
if (edad <= 0 || edad >= 120) {
errorEdad.textContent = 'La edad debe ser mayor que 0 y menor que 120.';
esValido = false;
}
}
if (!mensaje) {
errorMensaje.textContent = 'El mensaje no puede estar vacío.';
esValido = false;
}
if (esValido) {
formResultado.textContent = 'Formulario enviado con éxito.';
nombreInput.value = '';
edadInput.value = '';
mensajeInput.value = '';
}
});

View File

@@ -21,3 +21,15 @@ div {
color: #ffffff;
}
.error {
color: #b30000;
font-size: 0.9em;
display: block;
margin-top: 4px;
}
.success {
color: #0a6f0a;
font-weight: bold;
margin-top: 10px;
}

View File

@@ -38,7 +38,25 @@
</div>
<hr>
<div id="ejercicio-5">
<!-- Agregar acá el código HTML que haga falta para el ejercicio 5 -->
<form id="formulario">
<div>
<label for="nombre">Nombre:</label>
<input type="text" id="nombre" />
<span class="error" id="errorNombre"></span>
</div>
<div>
<label for="edad">Edad:</label>
<input type="text" id="edad" />
<span class="error" id="errorEdad"></span>
</div>
<div>
<label for="mensaje">Mensaje:</label>
<textarea id="mensaje"></textarea>
<span class="error" id="errorMensaje"></span>
</div>
<button type="submit">Enviar</button>
</form>
<p class="success" id="formResultado"></p>
</div>
<script src="clase-9.js"></script>
</body>