Skip to main content

Overview

The data validation API provides functions to validate user input, ensure data integrity, and display error messages to users.

validarFormulariosVehiculos()

Validates that all vehicle forms have complete and valid data before processing. Source: script.js:167-184

Parameters

This function takes no parameters. It validates based on the global numeroAutos variable.

Returns

boolean - Returns true if all forms are valid, false otherwise

Validation Checks

For each vehicle (1 to numeroAutos):
  1. Motorization Selection: Verifies that a motorization radio button is selected
  2. ITV Status Selection: Verifies that an ITV status radio button is selected
If validation fails, mostrarError() is automatically called with a specific error message indicating which vehicle and field needs attention.

Example Implementation

function validarFormulariosVehiculos() {
    for (let i = 1; i <= numeroAutos; i++) {
        // Verificar motorización
        const motorizacionSeleccionada = document.querySelector(
            `input[name="motorizacion${i}"]:checked`
        );
        if (!motorizacionSeleccionada) {
            mostrarError(`Por favor, seleccione la motorización para el vehículo ${i}.`);
            return false;
        }

        // Verificar estado ITV
        const itvSeleccionado = document.querySelector(
            `input[name="aprobados${i}"]:checked`
        );
        if (!itvSeleccionado) {
            mostrarError(`Por favor, seleccione el estado ITV para el vehículo ${i}.`);
            return false;
        }
    }
    return true;
}

Usage

if (validarFormulariosVehiculos()) {
    // Proceed with calculation
    procesarDatosVehiculos();
} else {
    // Validation failed, error already displayed
    return;
}

mostrarError()

Displays a styled error message to the user in a fixed notification. Source: script.js:381-464

Parameters

mensaje
string
required
The error message to display to the user

Returns

void - Does not return a value

Side Effects

  • Creates a fixed-position error alert in the top-right corner
  • Removes any existing error alerts before showing the new one
  • Automatically dismisses after 5 seconds
  • Injects CSS styles if not already present
  • Adds close button for manual dismissal

Alert Features

  • Position: Fixed top-right (20px from edges)
  • Animation: Slides in from the right
  • Auto-dismiss: 5 seconds
  • Manual close: Click the × button
  • Styling: Red gradient background with warning icon

Example Implementation

function mostrarError(mensaje) {
    // Remover alertas anteriores
    const alertaAnterior = document.querySelector(".alert-error");
    if (alertaAnterior) {
        alertaAnterior.remove();
    }

    // Crear nueva alerta
    const alerta = document.createElement("div");
    alerta.className = "alert-error";
    alerta.innerHTML = `
        <div class="alert-content">
            <span class="alert-icon">⚠️</span>
            <span class="alert-message">${mensaje}</span>
            <button class="alert-close" 
                    onclick="this.parentElement.parentElement.remove()">×</button>
        </div>
    `;

    // Agregar estilos dinámicamente si no existen
    if (!document.querySelector("#alert-styles")) {
        const estilos = document.createElement("style");
        estilos.id = "alert-styles";
        estilos.textContent = `
            .alert-error {
                position: fixed;
                top: 20px;
                right: 20px;
                background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
                border: 2px solid #ef4444;
                border-radius: 0.75rem;
                padding: 1rem;
                box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
                z-index: 1000;
                max-width: 400px;
                animation: slideIn 0.3s ease-out;
            }
            /* Additional styles... */
        `;
        document.head.appendChild(estilos);
    }

    document.body.appendChild(alerta);

    // Auto-remover después de 5 segundos
    setTimeout(() => {
        if (alerta.parentElement) {
            alerta.style.animation = "slideIn 0.3s ease-out reverse";
            setTimeout(() => alerta.remove(), 300);
        }
    }, 5000);
}

Usage Examples

// Missing required field
mostrarError("Por favor, complete todos los campos obligatorios.");

// Invalid number range
mostrarError("Por favor, ingrese un número válido de vehículos (1-50).");

// Missing vehicle data
mostrarError("Por favor, seleccione la motorización para el vehículo 3.");

inicializarEventos()

Sets up real-time validation and input enhancement for form fields. Source: script.js:487-516

Parameters

This function takes no parameters.

Returns

void - Does not return a value

Event Listeners

This function adds the following event listeners:

1. Number of Vehicles Input Validation

  • Event: input
  • Field: #nAutos
  • Validation:
    • Maximum value: 50
    • Minimum value: 0
    • Shows error if exceeded

2. Numeric Keypress Filter

  • Event: keypress
  • Field: #nAutos
  • Behavior: Only allows numeric input (0-9)

3. Text Capitalization

  • Event: input
  • Fields: #nombre, #apellidos, #razonSocial
  • Behavior: Automatically capitalizes first letter

Example Implementation

function inicializarEventos() {
    // Validación en tiempo real para el número de vehículos
    const nAutosInput = document.getElementById("nAutos");
    nAutosInput.addEventListener("input", function() {
        const valor = parseInt(this.value);
        if (valor > 50) {
            this.value = 50;
            mostrarError("El número máximo de vehículos es 50.");
        }
        if (valor < 0) {
            this.value = "";
        }
    });

    // Permitir solo números en el campo de vehículos
    nAutosInput.addEventListener("keypress", function(e) {
        if (!/[0-9]/.test(e.key) && 
            !['Backspace', 'Delete', 'Tab', 'Enter'].includes(e.key)) {
            e.preventDefault();
        }
    });

    // Capitalizar automáticamente nombres y apellidos
    const camposTexto = ['nombre', 'apellidos', 'razonSocial'];
    camposTexto.forEach(campo => {
        const input = document.getElementById(campo);
        input.addEventListener("input", function() {
            this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1);
        });
    });
}

Initialization

// Called automatically when DOM is ready
document.addEventListener("DOMContentLoaded", function() {
    inicializarEventos();
});
This function is automatically called on DOMContentLoaded to ensure all validation is active when the page loads.

Validation Constants

Vehicle Number Limits

  • Minimum: 1 vehicle
  • Maximum: 50 vehicles
  • Type: Integer only

Text Field Requirements

  • nombre: Required, auto-capitalized
  • apellidos: Required, auto-capitalized
  • razonSocial: Required, auto-capitalized

Vehicle Form Requirements

For each vehicle:
  • Motorization: Required (one of: Diesel, Gasolina, Híbrido, Eléctrico)
  • ITV Status: Required (one of: Aprobado, No Aprobado)
  • Observaciones: Optional, max 250 characters

Error Messages

Validation ErrorMessage
Missing client fields”Por favor, complete todos los campos obligatorios.”
Invalid vehicle number”Por favor, ingrese un número válido de vehículos (1-50).”
Vehicle count exceeded”El número máximo de vehículos es 50.”
Missing motorization”Por favor, seleccione la motorización para el vehículo .”
Missing ITV status”Por favor, seleccione el estado ITV para el vehículo .”
Calculation error”Ha ocurrido un error al procesar los datos. Por favor, verifique la información ingresada.”

Build docs developers (and LLMs) love