Conditions
Conditions are arguably the most powerful part of @zuze/schema. Some methods to handle conditional validations is present in virtually all schemas, but @zuze/schema aims to to boil complicated conditional logic when it comes to schema validation down to a very simple and intuitive API (especially via the AST)
Schemas can be conditional based on two properties,
- fields somewhere in the value being validated or
- context.
Both of which are accessible via refs
Creating Conditions#
There are multiple supported syntaxes to create conditions, almost all of which are based on a WTO (when-then-otherwise) concept. Arguably the easiest to understand is AST format.
Functional#
when can accept two arguments, the first is a string (or an array of strings) and the second is a function that accepts the resolved values of the specified dependencies and the original schema.
when can also accept an object format as it's second argument
AST Syntax#
The AIM of AST syntax is to be extremely readable:
conditions is an array and you can create as many conditions as you need. They will be evaluated in the order they were added to the SchemaDefinition.
Refs#
A ref (i.e. reference) is a pointer to a sibling/ancestor in the value that is being validated or a value from context. They are used in validators (where supported) and to resolve conditional schemas.
Refs are also accessed via the path notation using getter from property-expr
- ast
- functional
Sibling#
Sibling references are accessed by specifying the object property.
- ast
- functional
Context#
Context can also be used to resolve conditions. Context is accessed using a special prefix ($ by default, but this can be changed by setting the contextPrefix option when casting/validating a schema).
- ast
- functional
Relative Refs (!)#
Relative refs allow access to ancestors schemas/values from a child schema. They are defined by prefixing with a ref with a .. Every . in the prefix goes up "one level" of schema.
Casting the below object schema results in the following output:
- ast
- functional