Validation library for Lua with fluent API and error message handling inspired by Respect\Validation.
You can install it by using LuaRocks.
luarocks install validation
The fluent API of library follows the same principles of Respect\Validation.
After installing LuaValidation you can simple import it:
local v = require("validation")
It is possible to use validators in a chain.
v.numeric().positive().between(1, 256)
There are more than only one way to perform validation against you data with LuaValidation:
assert()
check()
validate()
This function validates the entire chain and produces its message.
v.numeric().positive().between(1, 256):assert(0)
The code above should produce this message:
Some rules must pass for "0"
- "0" must be positive
- "0" must be between "1" and "256"
Works like assert()
but is produces only the message of the first rule of the
rule which did not pass the validation.
v.numeric().positive():check(nil)
The code above should produce this message:
"nil" must be numeric
This function returns a boolean value which says if the input is valid or not.
if v.equals("foo"):validate(input) then
-- Do something
end
Once created, you can reuse your chain anywhere:
local my_chain = v.numeric().positive().between(1, 256)
my_chain:check(first)
my_chain:check(second)
my_chain:check(third)
By default you it uses error()
as default message handler, but you change this
behavior by defining a new messager with v.set_messager()
which accepts a
callback as an argument.
v.set_messager(
function (message)
print(">>>", message)
end
)
When you use assert()
and check()
, you can define a custom message for you
message:
v.numeric():check(nil, {message = "Something is not right"})
The above code produces this message:
Something is not right
When you use assert()
and check()
, sometimes you just want to name it:
v.numeric():check(nil, {name = "Name"})
The above code produces this message:
"Name" must be numeric
absent()
: Checks if the input isnil
all(...)
: Performs validation of all rules defined on its constructor against the inputbetween(minimum, maximum)
: Checks if the input is betweenminimum
andmaximum
dummy(result)
: Performs validation exactly according to what was defined asresult
on its constructorequals(expected)
: Checks if the input is equal to theexpected
valuekey(key, rule, mandatory)
: Performs validation ofrule
against the value ofkey
of the input. Ifmandatory
istrue
(which is the default value), also checks if thekey
exists in the input.never(rule)
: Performs the reverse validation of therule
in the given inputnumber()
: Checks if the input is a numbernumeric()
: Checks if the input is a numeric valuepositive()
: Checks if the input is a positive valuestring()
: Checks if the input is a string
There's just a few rules, but soon there will be as much as on Respect\Validation, if you want to contribute it will be a pleasure for me.