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:

LUA
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   --> 1

What 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.

LUA
input = { order = { id = "SO-1", quantity = 3 } }

Steps

  1. Return ok: whether input.order has a text id and a whole-number quantity of at least 1.
  2. Add problems: how many problems there are.
  3. Add paths: the path of 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.