Skip to content

Validator

Source: shiva-fw/libs/validator/init.lua

Rule-based data validation with a Laravel-inspired pipe syntax.

Availability

Validator is a global in every shiva module (loaded by sh_init.lua). No import required.

Validating Data

Validator.validate(data, rules)

Validate a data table against a rules table. Returns a ValidationResult.

lua
local result = Validator.validate(input, {
    name   = 'required|string|min:2|max:50',
    amount = 'required|number|min:1',
    reason = 'string',
})

if result:fails() then
    Log.warn('economy', result:firstError())
    return
end

Built-in Rules

RuleDescription
requiredField must be present and non-nil
stringMust be a string
numberMust be a number
integerMust be an integer
booleanMust be a boolean
tableMust be a table
min:nString min length or number min value
max:nString max length or number max value
between:min,maxNumber must be between min and max
in:a,b,cValue must be one of the listed options
emailMust match email format

ValidationResult

lua
result:passes()            -- boolean
result:fails()             -- boolean
result:errors()            -- table<field, string[]>
result:firstError(field?)  -- string|nil — first error for a field, or overall
result:allErrors()         -- string[] — flat list of all error messages

Custom Rules

Validator.extend(name, fn)

Register a custom validation rule.

lua
Validator.extend('positive', function(value, params)
    if type(value) ~= 'number' or value <= 0 then
        return false, 'must be a positive number'
    end
    return true
end)

-- Use it like any built-in rule
local result = Validator.validate(data, { amount = 'required|positive' })

Released under the MIT License.