Configuration Validator Based on Schema Described in Lua Tables

Lua configuration validator using schema tables to check required fields, types, arrays, and provide detailed error messages for validation.

Brief Introduction

Configuration Validator Based on Schema Described in Lua Tables (lua)
DESCRIPTION:
A complete example of a configuration validator in Lua that uses a schema defined through tables. The validator checks for the presence and type of required fields, supports basic types and arrays, and provides detailed error messages.

ADDITIONAL NOTES:
This example is ideal for validating configurations loaded from files or user input, ensuring they comply with a predefined schema. It can be extended to support more complex types or custom rules.

EXPLANATIONS:
- The function validateConfig takes as input the configuration to validate and the reference schema.
- The schema is a Lua table where each key represents a field, and the value is a table with the parameters 'type' and 'required'.
- The validator supports basic types: 'string', 'number', 'boolean', and 'array' (array of strings).
- If a field is mandatory and missing, an error is reported.
- If a field is present but does not match the expected type, an error is reported.
- For fields of type 'array', it checks that the value is an indexed table with string elements.
- The function returns two values: a boolean indicating if the validation passed, and a table with error messages.

Example Code: lua

-- Configuration validator based on schema described in Lua tables

-- Helper function to check if a table is an indexed array
local function isArray(t)
    if type(t) ~= "table" then return false end
    local count = 0
    for k, _ in pairs(t) do
        if type(k) ~= "number" then return false end
        count = count + 1
    end
    for i = 1, count do
        if t[i] == nil then return false end
    end
    return true
end

-- Main validation function
-- config: table with configuration to validate
-- schema: table with schema definition, e.g.: { field = {type="string", required=true} }
-- returns: boolean (true if valid), table with error messages
local function validateConfig(config, schema)
    local errors = {}
    for field, rules in pairs(schema) do
        local value = config[field]
        -- Check presence of required field
        if rules.required and value == nil then
            table.insert(errors, string.format("Field '%s' is missing but required.", field))
        elseif value ~= nil then
            local vtype = type(value)
            if rules.type == "string" then
                if vtype ~= "string" then
                    table.insert(errors, string.format("Field '%s' must be a string, found %s.", field, vtype))
                end
            elseif rules.type == "number" then
                if vtype ~= "number" then
                    table.insert(errors, string.format("Field '%s' must be a number, found %s.", field, vtype))
                end
            elseif rules.type == "boolean" then
                if vtype ~= "boolean" then
                    table.insert(errors, string.format("Field '%s' must be a boolean, found %s.", field, vtype))
                end
            elseif rules.type == "array" then
                if not isArray(value) then
                    table.insert(errors, string.format("Field '%s' must be an array of strings.", field))
                else
                    -- Check that all elements are strings
                    for i, elem in ipairs(value) do
                        if type(elem) ~= "string" then
                            table.insert(errors, string.format("Element %d of '%s' is not a string.", i, field))
                        end
                    end
                end
            else
                table.insert(errors, string.format("Type '%s' for field '%s' is not supported.", tostring(rules.type), field))
            end
        end
    end
    return (#errors == 0), errors
end

-- Example configuration schema
local schema = {
    nome = { type = "string", required = true },
    versione = { type = "number", required = true },
    abilitato = { type = "boolean", required = false },
    componenti = { type = "array", required = true }
}

-- Example configuration to validate
local config = {
    nome = "SistemaX",
    versione = 1.2,
    abilitato = true,
    componenti = { "sensore", "attuatore", "comunicazione" }
}

-- Configuration validation
local valido, errori = validateConfig(config, schema)
if valido then
    print("Configuration is valid.")
else
    print("Configuration is not valid:")
    for _, msg in ipairs(errori) do
        print(" - " .. msg)
    end
end

-- Example of invalid configuration
local config_errata = {
    nome = 123, -- wrong type
    -- versione missing
    abilitato = "si", -- wrong type
    componenti = { "sensore", 42, "comunicazione" } -- non-string element
}

local valido2, errori2 = validateConfig(config_errata, schema)
if valido2 then
    print("Configuration is valid.")
else
    print("Configuration is not valid:")
    for _, msg in ipairs(errori2) do
        print(" - " .. msg)
    end
end
×
×
×
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?

Hardware: No hardware components required, it is standalone software.

Software: Lua 5.3 or higher.

Dependencies: No external libraries required, the code is fully standalone.

Configuration: The validation schema is defined as a Lua table specifying type and requiredness.

Output: The validator returns true/false and detailed error messages for each invalid field.

Similar Topics