Skip to main content
The validation system in Seguros NAG ensures that all quote requests contain valid, complete data before submission. It’s located in lib/validators.ts and integrates with the insurance configuration.

The validarCotizacion Function

The main validation function accepts a form submission and returns an object containing any validation errors:
lib/validators.ts
export function validarCotizacion(
  tipoSeguro: string,
  formData: any
) {
  const errores: Record<string, string> = {};

  if (!tipoSeguro) {
    errores.tipoSeguro = "Seleccioná un tipo de seguro";
  }

  if (!formData.nombre?.trim()) {
    errores.nombre = "Falta ingresar nombre";
  }

  if (!formData.email?.trim()) {
    errores.email = "Falta ingresar email";
  } else {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      errores.email = "Ingresá un email válido";
    }
  }

  if (!formData.telefono?.trim()) {
    errores.telefono = "Falta ingresar teléfono";
  } else {
    const telefonoRegex = /^\d{8,}$/;
    if (!telefonoRegex.test(formData.telefono)) {
      errores.telefono = "Ingresá un teléfono válido (mínimo 8 dígitos)";
    }
  }

  const config = segurosConfig[tipoSeguro as keyof typeof segurosConfig];

  if (!config) return errores;

  config.campos.forEach((campo) => {
    const valor = formData[campo.name];

    if (campo.required && !valor) {
      errores[campo.name] = `Falta completar ${campo.label}`;
      return;
    }

    // Validaciones para campos number
    if (campo.type === "number" && valor) {
      const numero = Number(valor);

      if (campo.min !== undefined && numero < campo.min) {
        errores[campo.name] = `El mínimo permitido es ${campo.min}`;
      }

      if (campo.max !== undefined && numero > campo.max) {
        errores[campo.name] = `El máximo permitido es ${campo.max}`;
      }
    }
  });

  return errores;
}

Validation Rules

Base Field Validation

All quote forms require these base fields:
if (!tipoSeguro) {
  errores.tipoSeguro = "Seleccioná un tipo de seguro";
}
Ensures a valid insurance type is selected before processing.
if (!formData.nombre?.trim()) {
  errores.nombre = "Falta ingresar nombre";
}
Checks that the name field is not empty after trimming whitespace.
if (!formData.email?.trim()) {
  errores.email = "Falta ingresar email";
} else {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(formData.email)) {
    errores.email = "Ingresá un email válido";
  }
}
Validates email format using a regex pattern:
  • Must contain @ symbol
  • Must have domain with .
  • No whitespace allowed
if (!formData.telefono?.trim()) {
  errores.telefono = "Falta ingresar teléfono";
} else {
  const telefonoRegex = /^\d{8,}$/;
  if (!telefonoRegex.test(formData.telefono)) {
    errores.telefono = "Ingresá un teléfono válido (mínimo 8 dígitos)";
  }
}
Phone validation rules:
  • Minimum 8 digits
  • Only numeric characters
  • No spaces or special characters

Dynamic Field Validation

Fields defined in the insurance configuration are validated dynamically:

Required Field Check

lib/validators.ts
if (campo.required && !valor) {
  errores[campo.name] = `Falta completar ${campo.label}`;
  return;
}
If a field is marked as required: true in the configuration, this validation ensures it has a value.

Number Field Validation

lib/validators.ts
if (campo.type === "number" && valor) {
  const numero = Number(valor);

  if (campo.min !== undefined && numero < campo.min) {
    errores[campo.name] = `El mínimo permitido es ${campo.min}`;
  }

  if (campo.max !== undefined && numero > campo.max) {
    errores[campo.name] = `El máximo permitido es ${campo.max}`;
  }
}
For numeric fields with min or max constraints:
  • Converts the value to a number
  • Checks against minimum value if defined
  • Checks against maximum value if defined

Error Message Structure

Validation errors are returned as a Record<string, string> where:
  • Key: Field name (e.g., "nombre", "email", "edad")
  • Value: User-friendly error message in Spanish

Example Error Object

{
  "tipoSeguro": "Seleccioná un tipo de seguro",
  "email": "Ingresá un email válido",
  "edad": "El mínimo permitido es 18"
}

Usage in Forms

The validation function is called before submitting the form:
app/components/CotizacionForm.tsx
import { validarCotizacion } from "@/lib/validators";

const handleEmail = async () => {
  // Run validation
  const nuevosErrores = validarCotizacion(tipoSeguro, formData);

  // Check if there are errors
  if (Object.keys(nuevosErrores).length > 0) {
    setErrors(nuevosErrores);
    return; // Stop submission
  }

  // Clear errors and proceed
  setErrors({});
  
  // ... continue with submission
};

Displaying Validation Errors

Errors are displayed inline below each form field:
app/components/CotizacionForm.tsx
<input
  type="text"
  name="nombre"
  placeholder="Nombre Completo"
  value={formData.nombre}
  onChange={handleChange}
  className={`inputStyle ${errors.nombre ? "border-red-500" : ""}`}
/>
<div className="min-h-[20px]">
  {errors.nombre && (
    <p className="text-red-500 text-sm mt-1">
      {errors.nombre}
    </p>
  )}
</div>

Visual Feedback

Red Border

Fields with errors receive a border-red-500 class for visual emphasis.

Error Message

Error text appears below the field in red with proper spacing.

Validation Examples

{
  tipoSeguro: "automotor",
  nombre: "Juan Pérez",
  email: "[email protected]",
  telefono: "1145678901",
  marca: "Ford",
  modelo: "Focus",
  anio: 2020,
  uso: "particular",
  localidad: "Buenos Aires"
}
// Result: {} (no errors)

Best Practices

1

Validate on Submit

Always call validarCotizacion before processing form submissions (email or WhatsApp).
2

Show All Errors

Display all validation errors simultaneously so users can fix multiple issues at once.
3

Clear Errors Appropriately

Clear the error state after successful validation or when the user starts correcting a field.
4

Use Friendly Messages

Error messages use informal Spanish (“vos” form) to match the site’s tone.
5

Prevent Multiple Submissions

Disable submit buttons during validation and submission to prevent duplicate requests.

Extending Validation

To add custom validation rules:
  1. Add validation logic in lib/validators.ts
  2. Return appropriate error messages in the errores object
  3. Display errors in the form component

Example: Adding CPF/CUIT Validation

lib/validators.ts
if (formData.cuit?.trim()) {
  const cuitRegex = /^\d{2}-\d{8}-\d{1}$/;
  if (!cuitRegex.test(formData.cuit)) {
    errores.cuit = "Ingresá un CUIT válido (formato: 20-12345678-9)";
  }
}

Build docs developers (and LLMs) love