Logic Schema
This is not a new data type but a logical wrapper around other types.
It allows you to combine different schema settings using different logical operators. This gives you the possibility to define alternatives or put different schema in queue together like String sanitization with number conversion.
See at Base Schema for the inherited methods you may call like:
title()
detail()
default()
stripEmpty()
raw()
1. Schema combination
It is possible to put multiple schemas together with logical AND and OR.
1.1. allow(schema) / deny(schema)
Such logic queues can be started in two ways. As a positive queue using allow()
to only select the
ones which succeeds the logic. Or as a negative queue using deny()
to only allow the settings
which will not succeed in logic.
const schema = new LogicSchema()
.allow(new StringSchema().replace(/_/g, '', 'remove _'))
.and(new NumberSchema())
const schema = new LogicSchema()
.deny(new StringSchema().match(/6[01]6/)) // deny '606' + '616' (string)
.or(new NumberSchema().positive.max(99)) // deny 0..99 (number)
1.2. and(schema) / or(schema)
The logical queue is processed in the following precedence: AND
, OR
and top down.
This is the same as in most programming languages. If you need braces use a sub logic schema which
does exactly this.
You can use both operators multiple times:
- AND here both schema definitions have to validate. They will run serial so that the later ones get the changed values from the earlier.
- OR at least one of the schema definitions has to validate.
2. Conditionals
It is also possible to use a schema as a conditional operator and decide how to validate depending on it's result, if it succeeds or fails. This is in the same way normal if..then..else conditions work.
const schema = new ObjectSchema()
.key('init',
new LogicSchema()
.if(new NumberSchema(new Reference().path('/start')).min(1))
.then(new AnySchema().forbidden())
.else(new AnySchema().required()),
)
const data = {
start: 3,
init: 'already running',
}
2.1. if(schema)
This starts the conditional check with a schema which may validate or not. The concrete result data doesn't matter because it is only used to decide which part is used.
2.2. then(schema) / else(schema)
Depending if the if(schema)
succeeds the then
or the else
part is used on the original data.