Skip to content

Validation

Use the Validator API to validate all inputs — config values, command arguments, net event data, and API requests.

Basic Validation

lua
local Validator = require('shiva-fw.validator')

local schema = Validator.schema({
    playerId = { type = 'number', required = true, min = 1 },
    item     = { type = 'string', required = true, maxLength = 64 },
    count    = { type = 'number', required = true, min = 1, max = 100 },
})

local data, errors = schema:validate({
    playerId = source,
    item = 'fish_bass',
    count = 1,
})

if errors then
    -- errors is a table of { field, message } pairs
    for _, err in ipairs(errors) do
        print(err.field, err.message)
    end
    return
end

-- data is the validated and coerced value

Field Types

TypeValidates
'number'Lua number
'string'Lua string
'boolean'Lua boolean
'table'Lua table
'enum'One of a list of values

Field Options

OptionTypeDescription
requiredbooleanError if nil (default: false)
optionalbooleanAlias for required = false
minnumberMinimum value (numbers) or length (strings)
maxnumberMaximum value or length
minLengthnumberMinimum string length
maxLengthnumberMaximum string length
valuestableAllowed values for enum
patternstringLua pattern for string matching
defaultanyDefault value if nil

Nested Schemas

lua
local schema = Validator.schema({
    player = {
        type = 'table',
        schema = {
            id   = { type = 'number', required = true },
            name = { type = 'string', required = true },
        },
    },
})

Validating Net Events

Always validate data received from clients:

lua
RegisterNetEvent('my-module:castLine', function(rawData)
    local source = source
    local data, errors = castSchema:validate(rawData)
    if errors then
        -- silently ignore malformed client data
        return
    end
    -- safe to use data now
end)

See Also

Released under the MIT License.