aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--valua-test.lua11
-rw-r--r--valua.lua14
2 files changed, 19 insertions, 6 deletions
diff --git a/valua-test.lua b/valua-test.lua
index e358c77..307cd1a 100644
--- a/valua-test.lua
+++ b/valua-test.lua
@@ -42,13 +42,14 @@ local tests = {
{v:new().type("string").len(3,5), {1,false}},
{v:new().type("number").len(3,5), {1,false}},
{v:new().type("table").empty(), {15,true, 16,false, 1,false}},
+-- require('mobdebug').start('127.0.0.1')
{v:new().not_empty(), {2,true, 3,false, 4,false, 16,true, 5,true, 6,true}},
{v:new().len(2,10), {2,true}},
{v:new().type("number"), {2,false}},
{v:new().empty(), {3,true, 4,true, 5,false, 6,false}},
{v:new().boolean(), {1,false, 5,true}},
{v:new().compare("hey"), {1,false, 2,true}},
- {v:new().number().min(45), {2,false, 6,false, 7,true}},
+ {v:new().number().min(45), {2,false, 6,false, 7,true, 4,false}},
{v:new().number().max(1009), {7,false, 6,true}},
{v:new().date(), {9,false, 10,false, 11,true, 8,true}},
{v:new().date('us'), {8,false, 9,true}},
@@ -56,12 +57,14 @@ local tests = {
{v:new().in_list({"hey",42}), {12,false, 6,true, 2,true}},
{v:new().match("^%d+%p%d+%p%d%d%d%d$"), {1,false, 8,true}},
{v:new().alnum(), {8,false, 13,true}},
- {v:new().integer(), {14,false, 6,true}},
- {v:new().string(), {14,false, 1,true}},
+ {v:new().integer(), {14,false, 6,true,}},
+ {v:new().string(), {14,false, 1,true, 4,false}},
{v:new().string().alnum(), {6,false}},
{v:new().contains(" "), {2,false, 1,true}},
{v:new().no_white(), {1,false, 2,true}},
- {v:new().datetime(), {19,true, 9,false}}
+ {v:new().datetime(), {19,true, 9,false}},
+ {v:new().number().min(45).optional(), {2,false, 6,false, 7,true, 4,true}},
+ {v:new().string().optional(), {14,false, 1,true, 4,true}},
}
for n,t in ipairs(tests) do
diff --git a/valua.lua b/valua.lua
index 6e1c6e4..11d4741 100644
--- a/valua.lua
+++ b/valua.lua
@@ -41,8 +41,12 @@ function valua:new(obj)
--saves a function named _<index> with its args in a funcs table, to be used later when validating
return function(...)
local args = pack(...)
- local f = function(value) return valua['_'..k](value, unpack(args, 1, args.n)) end
- tinsert(t.funcs,f)
+ if k == 'optional' then
+ obj.allow_nil = true
+ else
+ local f = function(value) return valua['_'..k](value, unpack(args, 1, args.n)) end
+ tinsert(t.funcs,f)
+ end
return t
end
end
@@ -51,6 +55,11 @@ function valua:new(obj)
self.__call = function(t,value)
local res = true
local fres, err
+
+ if value == nil and t.allow_nil then
+ return res, err
+ end
+
-- iterates through all chained validations funcs that were packed, passing the value to be validated
for _,f in ipairs(t.funcs) do
fres,err = f(value)
@@ -64,6 +73,7 @@ function valua:new(obj)
return res,err
end
obj.funcs = {}
+ obj.allow_nil = false
return obj
end
--