Skip to content

Commit 6708967

Browse files
committed
chore(docs): update the documentation, add example
1 parent 723157e commit 6708967

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

examples/errors.lua

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
-- This example shows how to collect either the first error or all errors
2+
-- during validation.
3+
4+
local jsonschema = require 'resty.ljsonschema'
5+
6+
local my_schema = {
7+
type = "object",
8+
properties = {
9+
name = {
10+
type = "string",
11+
minLength = 3
12+
},
13+
age = {
14+
type = "integer",
15+
minimum = 0
16+
},
17+
email = {
18+
type = "string",
19+
pattern = "^[^@]+@[^@]+$"
20+
}
21+
},
22+
required = { "name", "age" }
23+
}
24+
25+
-- Generate two validators: one that stops at the first error, and one that
26+
-- collects all errors.
27+
local validator_single = jsonschema.generate_validator(my_schema)
28+
local validator_all = jsonschema.generate_validator(my_schema, { collect_all_errors = true })
29+
30+
-- Now define values to validate against our spec:
31+
local my_data = {
32+
name = 'Al',
33+
age = -42.1,
34+
email = 'invalid-email'
35+
}
36+
37+
-- requires Penlight library for pretty printing tables
38+
local pl_pretty = require 'pl.pretty'
39+
print("single: " .. pl_pretty.write({validator_single(my_data)})) --> false, error message
40+
print("all: " .. pl_pretty.write({validator_all(my_data)})) --> false, table of all error messages

src/resty/ljsonschema/init.lua

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1223,11 +1223,10 @@ local _M = {
12231223
-- There is no default implementation: this function must be provided if
12241224
-- resolving external schemas is required. The function signature should be: `function(url)`
12251225
-- @tparam[opt] bool custom.collect_all_errors If set to true, the validator will collect all validation errors
1226-
-- instead of stopping at the first one. The error message contains:
1227-
-- * schema_path: Path to the JSON Schema keyword that failed validation.
1228-
-- * instance_path: Path to the value that failed validation.
1229-
-- * error: The error message.
1230-
--
1226+
-- instead of stopping at the first one. Each error entry contains:
1227+
-- `schema_path` (path to the JSON Schema keyword that failed validation),
1228+
-- `instance_path` (path to the value that failed validation), and
1229+
-- `error` (the error message).
12311230
-- @tparam[opt=false] bool custom.coercion There are cases where incoming data will always be strings. For example
12321231
-- when validating http-headers or query arguments.
12331232
-- For these cases there is this option `coercion`. If you set this flag then

0 commit comments

Comments
 (0)