diff --git a/clase-9.js b/clase-9.js index 4f32c34..5a5d7f7 100644 --- a/clase-9.js +++ b/clase-9.js @@ -53,4 +53,63 @@ insideButton.addEventListener('click', () => { outside.addEventListener('click', () => { console.log("outside capturing"); -}, true); \ No newline at end of file +}, true); + +// Ejercicio 5 + +const userForm = document.getElementById('userForm'); +const nameInput = document.getElementById('nameInput'); +const ageInput = document.getElementById('ageInput'); +const messageInput = document.getElementById('messageInput'); + +const clearErrors = () => { + document.getElementById('nameError').textContent = ''; + document.getElementById('ageError').textContent = ''; + document.getElementById('messageError').textContent = ''; +} + +const validateForm = () => { + let isValid = true; + + if (nameInput.value.trim() === '') { + document.getElementById('nameError').textContent = 'El nombre es obligatorio.'; + isValid = false; + } + + const age = parseInt(ageInput.value); + if (isNaN(age) || age < 0 || age > 120) { + document.getElementById('ageError').textContent = 'La edad debe ser un número entre 0 y 120.'; + isValid = false; + } + + if (messageInput.value.trim() === '') { + document.getElementById('messageError').textContent = 'El mensaje es obligatorio.'; + isValid = false; + } + + return isValid; +} + +const showSuccessMessage = () => { + alert('Formulario enviado con éxito!'); +} + +const clearForm = () => { + nameInput.value = ''; + ageInput.value = ''; + messageInput.value = ''; +} + +const handleSubmit = (event) => { + event.preventDefault(); + + clearErrors(); + + const isValid = validateForm(); + + if (isValid) { + showSuccessMessage(); + clearForm(); +}} + +userForm.addEventListener('submit', handleSubmit); \ No newline at end of file diff --git a/estilo.css b/estilo.css index e0ce57c..b7d70a3 100644 --- a/estilo.css +++ b/estilo.css @@ -14,4 +14,14 @@ li { font-weight: bold; border-radius: 6px; padding: 4px 8px; +} + +.errorMessage { + color: red; + font-size: 14px; +} + +#successMessage { + color: green; + font-weight: bold; } \ No newline at end of file diff --git a/index.html b/index.html index 90ba7fb..3f1d364 100644 --- a/index.html +++ b/index.html @@ -47,7 +47,27 @@