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
endBuilt-in Rules
| Rule | Description |
|---|---|
required | Field must be present and non-nil |
string | Must be a string |
number | Must be a number |
integer | Must be an integer |
boolean | Must be a boolean |
table | Must be a table |
min:n | String min length or number min value |
max:n | String max length or number max value |
between:min,max | Number must be between min and max |
in:a,b,c | Value must be one of the listed options |
email | Must 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 messagesCustom 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' })