Lua Table-Based Rules Engine for Validating Structured Data

Lua table-based rules engine for validating structured data with customizable rules, error messages, and support for common data types.

Brief Introduction

Lua Table-Based Rules Engine for Validating Structured Data (lua)
DESCRIPTION:
A simple and modular rules engine written in Lua that uses tables to define validation rules on structured data (e.g., configuration tables or JSON-like data). The system allows defining multiple rules for each field, with custom error messages and support for common data types.

ADDITIONAL NOTES:
This rules engine is designed to be easily extendable and adaptable to different types of structured data. It can be used to validate configuration data, user input, or data coming from sensors or external APIs. The modular structure allows easy addition of new rules or validation types.

EXPLANATIONS:
- The 'rules' table defines which rules to apply for each field, such as type, whether it is required, numeric range, minimum or maximum length, regex pattern, and custom error messages.
- The 'validate' function receives the data and rules, iterates over each field, and applies the defined rules, collecting any errors in a table.
- Support functions like 'check_type', 'check_range', 'check_length', and 'check_pattern' implement individual validation rules.
- The code is commented in Italian to facilitate understanding and maintenance.

Example Code: lua

-- Lua table-based rules engine for validating structured data

-- Function to check the type of a value
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
    -- Unsupported type
    return false
  end
end

-- Function to check if a number is within a range [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

-- Function to check the length of a string
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

-- Function to check a regex pattern (using string.match)
local function check_pattern(value, pattern)
  if type(value) ~= "string" then return false end
  return string.match(value, pattern) ~= nil
end

-- Main validation function
-- data: table with data to validate
-- rules: table with validation rules
-- Returns: table with errors, key by key
local function validate(data, rules)
  local errors = {}

  for field, rule in pairs(rules) do
    local value = data[field]

    -- Required check
    if rule.required and value == nil then
      errors[field] = rule.message or ("Field '" .. field .. "' is required.")
    else
      -- If field is not present and not required, skip
      if value == nil then
        -- nothing to validate
      else
        -- Type check
        if rule.type then
          if not check_type(value, rule.type) then
            errors[field] = rule.message or ("Field '" .. field .. "' must be of type " .. rule.type .. ".")
          end
        end

        -- If no errors so far, proceed with other rules
        if not errors[field] then
          -- Numeric range check
          if rule.min or rule.max then
            if not check_range(value, rule.min, rule.max) then
              errors[field] = rule.message or ("Field '" .. field .. "' must be between " .. tostring(rule.min) .. " and " .. tostring(rule.max) .. ".")
            end
          end

          -- String length check
          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 ("Length of field '" .. field .. "' must be between " .. tostring(rule.min_length) .. " and " .. tostring(rule.max_length) .. " characters.")
            end
          end

          -- Regex pattern check
          if rule.pattern then
            if not check_pattern(value, rule.pattern) then
              errors[field] = rule.message or ("Field '" .. field .. "' does not match the required format.")
            end
          end
        end
      end
    end
  end

  return errors
end

-- Usage example
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 = "Name must be a string between 3 and 50 characters."
  },
  eta = {
    type = "integer",
    required = true,
    min = 18,
    max = 99,
    message = "Age must be an integer between 18 and 99."
  },
  email = {
    type = "string",
    required = true,
    pattern = "^[%w%.%-_]+@[%w%.%-_]+%.[a-zA-Z]+$",
    message = "Email is not valid."
  },
  attivo = {
    type = "boolean",
    required = false
  },
  codice = {
    type = "string",
    required = true,
    pattern = "^%u%u%d%d%d%d$", -- Two uppercase letters followed by 4 digits
    message = "Code must consist of two uppercase letters followed by four digits."
  }
}

-- Perform validation
local errori = validate(dati_da_validare, regole)

-- Print results
if next(errori) == nil then
  print("Validation passed without errors.")
else
  print("Validation errors:")
  for campo, errore in pairs(errori) do
    print(campo .. ": " .. errore)
  end
end

-- End of rules engine
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Software:
  • Lua 5.1 or higher (compatible with LuaJIT)
  • No external dependencies required
  • Configuration via Lua tables to define validation rules
Main components:
  • 'rules' table defining rules for each field (e.g., type, range, regex pattern, required)
  • validate(data, rules) function that performs validation and returns a table with errors
  • Support functions to validate types, numeric ranges, string lengths, and patterns
Links/Configurations:
  • To integrate with external systems, just provide the data to validate as a Lua table
  • Rules configuration is fully customizable via Lua tables
Arduino:
  • Not applicable (standalone Lua software)

Similar Topics