-
Notifications
You must be signed in to change notification settings - Fork 1
/
validation.lua
75 lines (66 loc) · 1.47 KB
/
validation.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
local utf8validate = require("utf8validate")
local validation = {}
local validators = {}
function validators.string(v) return type(v) == "string" end
function validators.number(v) return type(v) == "number" end
function validators.boolean(v) return type(v) == "boolean" end
function validators.integer(v) return math.floor(v) == v end
validators["#"] = function(v, a, b)
b = b or a
return #v >= a and #v <= b
end
validators["between"] = function(v, a, b)
b = b or a
return v >= a and v <= b
end
validators["*"] = function(v, ...)
for i = 1, select("#", ...) do
if not validation.validate(v, select(i, ...)) then
return false
end
end
return true
end
function validators.utf8(v)
return utf8validate(v) == v
end
function validators.one_of(v, ...)
for i = 1, select("#", ...) do
if v == select(i, ...) then
return true
end
end
return false
end
function validators.array_of(v, schema)
for _, _v in ipairs(v) do
if not validation.validate(_v, schema) then
return false
end
end
return true
end
function validation.validate(value, schema)
if not schema then
return true
end
if type(schema) == "string" then
if not validators[schema](value) then
return false
end
return true
end
if schema[1] then
if not validators[schema[1]](value, unpack(schema, 2)) then
return false
end
return true
end
for k, _schema in pairs(schema) do
if not validation.validate(value[k], _schema) then
return false
end
end
return true
end
return validation