feat: add form validation and submission handling for exercise 5
This commit is contained in:
61
clase-9.js
61
clase-9.js
@@ -53,4 +53,63 @@ insideButton.addEventListener('click', () => {
|
||||
|
||||
outside.addEventListener('click', () => {
|
||||
console.log("outside capturing");
|
||||
}, true);
|
||||
}, 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);
|
||||
Reference in New Issue
Block a user