Motor de reglas en Lua para validar datos estructurados con tablas, reglas personalizadas y soporte modular para configuraciones y APIs.
-- Motor de reglas basado en tablas Lua para validar datos estructurados
-- Función para comprobar el tipo de un valor
local function check_type(value, expected_type)
local t = type(value)
if expected_type == "number" then
return t == "number"
elseif expected_type == "string" then
return t == "string"
elseif expected_type == "boolean" then
return t == "boolean"
elseif expected_type == "table" then
return t == "table"
elseif expected_type == "integer" then
return t == "number" and math.floor(value) == value
else
-- Tipo no soportado
return false
end
end
-- Función para comprobar si un número está en un rango [min, max]
local function check_range(value, min_val, max_val)
if type(value) ~= "number" then return false end
if min_val and value < min_val then return false end
if max_val and value > max_val then return false end
return true
end
-- Función para comprobar la longitud de una cadena
local function check_length(value, min_len, max_len)
if type(value) ~= "string" then return false end
local len = #value
if min_len and len < min_len then return false end
if max_len and len > max_len then return false end
return true
end
-- Función para comprobar un patrón regex (usando string.match)
local function check_pattern(value, pattern)
if type(value) ~= "string" then return false end
return string.match(value, pattern) ~= nil
end
-- Función principal de validación
-- data: tabla con los datos a validar
-- rules: tabla con las reglas de validación
-- Retorna: tabla con errores, clave por clave
local function validate(data, rules)
local errors = {}
for field, rule in pairs(rules) do
local value = data[field]
-- Comprobación de obligatoriedad
if rule.required and value == nil then
errors[field] = rule.message or ("El campo '" .. field .. "' es obligatorio.")
else
-- Si el campo no está presente y no es obligatorio, saltar
if value == nil then
-- nada que validar
else
-- Comprobación de tipo
if rule.type then
if not check_type(value, rule.type) then
errors[field] = rule.message or ("El campo '" .. field .. "' debe ser de tipo " .. rule.type .. ".")
end
end
-- Si no hay errores hasta ahora, continúo con otras reglas
if not errors[field] then
-- Comprobación de rango numérico
if rule.min or rule.max then
if not check_range(value, rule.min, rule.max) then
errors[field] = rule.message or ("El campo '" .. field .. "' debe estar entre " .. tostring(rule.min) .. " y " .. tostring(rule.max) .. ".")
end
end
-- Comprobación de longitud de cadena
if rule.min_length or rule.max_length then
if not check_length(value, rule.min_length, rule.max_length) then
errors[field] = rule.message or ("La longitud del campo '" .. field .. "' debe estar entre " .. tostring(rule.min_length) .. " y " .. tostring(rule.max_length) .. " caracteres.")
end
end
-- Comprobación de patrón regex
if rule.pattern then
if not check_pattern(value, rule.pattern) then
errors[field] = rule.message or ("El campo '" .. field .. "' no coincide con el formato requerido.")
end
end
end
end
end
end
return errors
end
-- Ejemplo de uso
local dati_da_validare = {
nome = "Mario Rossi",
eta = 28,
email = "mario.rossi@example.com",
attivo = true,
codice = "AB1234"
}
local regole = {
nome = {
type = "string",
required = true,
min_length = 3,
max_length = 50,
message = "El nombre debe ser una cadena entre 3 y 50 caracteres."
},
eta = {
type = "integer",
required = true,
min = 18,
max = 99,
message = "La edad debe ser un número entero entre 18 y 99."
},
email = {
type = "string",
required = true,
pattern = "^[%w%.%-_]+@[%w%.%-_]+%.[a-zA-Z]+$",
message = "El email no es válido."
},
attivo = {
type = "boolean",
required = false
},
codice = {
type = "string",
required = true,
pattern = "^%u%u%d%d%d%d$", -- Dos letras mayúsculas seguidas de 4 dígitos
message = "El código debe estar formado por dos letras mayúsculas seguidas de cuatro dígitos."
}
}
-- Ejecuto la validación
local errori = validate(dati_da_validare, regole)
-- Imprimo los resultados
if next(errori) == nil then
print("Validación superada sin errores.")
else
print("Errores de validación:")
for campo, errore in pairs(errori) do
print(campo .. ": " .. errore)
end
end
-- Fin del motor de reglas