
emailField = document.getElementById('email');

function validateField(field) {
    // Eliminar cualquier mensaje de error anterior específico
    const existingError = field.parentNode.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }

    // Reiniciar estilos
    field.style.border = '2px solid #ccc';

    if (field.value.trim() === '') {
        const errorMessage = document.createElement('p');
        errorMessage.className = 'error-message';
        errorMessage.style.color = 'red';
        errorMessage.textContent = `${field.placeholder} is required`;
        field.style.border = '3px solid red';
        field.parentNode.appendChild(errorMessage);
        return false;
    }

    return true;
    
}

function validateEmail() {

    // Elimina mensaje de error previo si existe
    var existingError = emailField.parentNode.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }

    if (!validateField(emailField)) {
        return false;
    }

    var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailPattern.test(emailField.value.trim())) {
        errorMessage = document.createElement('p');
        errorMessage.className = 'error-message';
        errorMessage.style.color = 'red';
        errorMessage.textContent = "This email format is not valid";
        emailField.style.border = '3px solid red';
        emailField.parentNode.appendChild(errorMessage);
        return false;
    }

    return true;
}

emailField.onblur = function () {
    validateEmail();
};