Learn Lua · Time, IDs and checks · Lesson 4 of 4
Checking data
Data from outside can be any shape. validate.check compares a value with a schema:
a table that describes what you expect, such as which fields are required and what kind of
value each holds. It returns true or false, and a list of problems, each with a path
and a message:
local schema = {
type = "object",
required = { "id", "quantity" },
properties = { id = { type = "string" }, quantity = { type = "integer", minimum = 1 } },
}
validate.is_valid({ id = "SO-1", quantity = 3 }, schema) --> true
local ok, errors = validate.check({ id = "SO-1", quantity = 0 }, schema)
ok --> false
#errors --> 1What your code receives
Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.
input = { order = { id = "SO-1", quantity = 3 } }Steps
- Return
ok: whetherinput.orderhas a textidand a whole-numberquantityof at least 1. - Add
problems: how many problems there are. - Add
paths: thepathof each problem, in order.
Show a hint
Start from the schema in the example. validate.check gives two results, and
table.map can turn the list of problems into a list of paths.