Interface: BooleanSchema<TSchema>
A schema of booleans, built by DTO.Boolean(). With conversion enabled (strict(false)), the strings 'true' and 'false' (case-insensitively) and the values of truthy() and falsy() are accepted and converted to booleans.
Extends
AnySchema<TSchema>
Type Parameters
TSchema
TSchema = boolean
The type of the booleans the schema validates.
Properties
type?
optionaltype?:Types
The type name of the schema (string, object, bigint…).
Inherited from
Methods
allOf()
allOf(...
schemas):this
Require the value to also match every schema; their errors are reported, while the value they return (their conversions) is not kept.
Parameters
schemas
...SchemaLike[]
The schemas the value must match.
Returns
this
A new schema.
Inherited from
allow()
allow(...
values):this
Allow values, even when they fail the other rules of the schema (DTO.String().allow(null, '')). Also see valid(), which makes them the only values allowed.
Parameters
values
...any[]
The values allowed, compared by deep equality; references are resolved during the validation.
Returns
this
A new schema.
Inherited from
alter()
alter(
targets):this
Assign named alterations to the schema, applied to a copy of it when tailor() is called with their names.
Parameters
targets
Record<string, (schema) => Schema>
The adjusters by target name: each function takes the schema and returns the altered one.
Returns
this
A new schema.
Inherited from
artifact()
artifact(
id):this
Assign the schema an artifact id, collected when the rule passes and the artifacts validation option is on.
Parameters
id
any
Any value other than undefined, returned as-is in the result artifacts map.
Returns
this
A new schema.
Inherited from
cache()
cache(
cache?):this
Cache the validation results (successes and failures) of the inputs, for the primitive inputs only. The cache is only used when the cache validation option is true, which it is not by default.
Parameters
cache?
Cache
The cache to use. Defaults to a new cache of at most 1000 entries, dropping the least recently used.
Returns
this
A new schema.
Throws
When the schema already has a cache, or an artifact.
Inherited from
cast()
cast(
to):this
Cast the validated value to another type: map for an object schema, set for an array schema, number or string for a boolean, date or number schema.
Parameters
to
"string" | "number" | "set" | "map"
The type of the value returned.
Returns
this
A new schema.
Throws
When the type of the schema cannot cast to it.
Inherited from
concat()
concat(
schema):this
Merge another schema into this one: its rules, flags and allowed values are added to the ones of this schema.
Parameters
schema
this
A schema of the same type, or an any schema (DTO.Any()).
Returns
this
A new schema.
Throws
When the types differ (an any schema excepted).
Inherited from
custom()
custom(
fn,description?):this
Add a custom validation rule.
Parameters
fn
The rule: it returns the value to keep (undefined keeps it unchanged) or an error from helpers.error(); an error it throws fails the validation with the code any.custom and the error message.
description?
string
A description of the rule, shown by describe().
Returns
this
A new schema.
Inherited from
default()
default(
value?):this
Set a default value, used when the value is undefined. Unless the noDefaults validation option is on, the default is returned as the validated value (it is not validated itself).
Parameters
value?
Reference | BasicType | ((parent, helpers) => Reference | BasicType)
The default value: a literal, a reference (DTO.Ref('other')), or a function returning it, called with a clone of the parent object and the validation helpers (declare no parameters when you do not use them: the clone has a cost). An object is used by reference: changing it afterwards changes the default. Without a value, an object schema defaults to an object built from the defaults of its keys.
Returns
this
A new schema.
Inherited from
describe()
describe():
Description
Describe the schema as a plain object: its type, flags, rules, allowed values and annotations.
Returns
Description
The description.
Inherited from
description()
description(
desc):this
Set the description of the value, an annotation shown by describe() and written to the JSON Schemas.
Parameters
desc
string
The description, a non-empty string.
Returns
this
A new schema.
Inherited from
disallow()
disallow(...
values):this
Forbid values (an alias of invalid()).
Parameters
values
...any[]
The values forbidden, compared by deep equality.
Returns
this
A new schema.
Inherited from
empty()
empty(
schema?):this
Treat the values matching a schema as empty (undefined), like the empty string for an optional string: DTO.String().empty('').
Parameters
schema?
The schema, or the literal value, of the empty values. Without it, the rule is removed.
Returns
this
A new schema.
Inherited from
equal()
equal(...
values):this
Allow only the given values (an alias of valid()).
Parameters
values
...any[]
The only values allowed, compared by deep equality.
Returns
this
A new schema.
Inherited from
error()
error(
err):this
Replace the validation error of the schema when a rule fails.
Parameters
err
Error | ValidationErrorFunction
An Error, thrown as is without the details of the validation; or a function receiving the error reports and returning the new message (a string), error items (type, message or template, context) or an Error. When another error is found before this schema is validated, that error is the one reported (unless the abortEarly validation option is false).
Returns
this
A new schema.
Inherited from
example()
example(
value,options?):this
Add an example value, an annotation shown by describe() and written to the JSON Schemas.
Parameters
value
any
The example, which should be valid; not undefined.
options?
With override: true, the example replaces the ones added before.
override
boolean
Returns
this
A new schema.
Inherited from
exist()
exist():
this
Require the value: undefined is not allowed (an alias of required()).
Returns
this
A new schema.
Inherited from
external()
external(
method,description?):this
Add an external validation rule, which may be asynchronous (a database lookup). The external rules run after all the other rules of the whole value passed, and only then; their changes to the value are not seen by the other rules.
Parameters
method
ExternalValidationFunction
The rule: it returns the value to keep (undefined keeps it unchanged) or an error from helpers.error().
description?
string
A description of the rule, shown by describe().
Returns
this
A new schema.
Remarks
A schema with external rules must be validated by DTO.validateAsync(): the synchronous validation throws a SchemaDefinitionException, unless the externals validation option is false.
Inherited from
extract()
extract(
path):Schema
Get a sub-schema by its path of object keys or schema ids.
Parameters
path
string | string[]
A path separated by . ('address.city'), or its keys as an array. A key is the id set by id() or, without one, the object key.
Returns
The sub-schema.
Throws
When no sub-schema has the path.
Inherited from
failover()
failover(
value):this
Set a failover value, returned instead of an error when the value fails the validation.
Parameters
value
any
The failover value: a literal, a reference, or a function returning it (called with a clone of the parent object and the validation helpers: declare no parameters when you do not use them). An object is used by reference: changing it afterwards changes the failover.
Returns
this
A new schema.
Inherited from
falsy()
falsy(...
values):this
Accept other values as false, with conversion enabled (strict(false)). The strings are compared case-insensitively unless sensitive() is called.
Parameters
values
...(string | number | null)[]
The values converted to false: strings, numbers or null.
Returns
this
A new schema.
forbidden()
forbidden():
this
Forbid the value: only undefined is allowed. Used to reject a key of an object.
Returns
this
A new schema.
Inherited from
fork()
fork(
key,adjuster):this
Return a copy of the schema with the sub-schemas at the given paths replaced by an adjusted version.
Parameters
key
string | string[] | string[][]
The path of a sub-schema ('a.b'), several paths, or paths as arrays of keys.
adjuster
The function returning the new sub-schema from the current one, like (schema) => schema.required().
Returns
this
A new schema.
Throws
When a path reaches no sub-schema.
Inherited from
id()
id(
name?):this
Set the id of the schema, which extract(), fork() and the links (DTO.Link('#id')) reach it by. Without an id, a key of an object schema is reached by its key; a schema in an array or alternatives cannot be reached. The JSON Schemas write a schema with an id as a shared definition.
Parameters
name?
string
The id, without .. Without it, the id is removed.
Returns
this
A new schema.
Throws
When the id contains a ..
Inherited from
invalid()
invalid(...
values):this
Forbid values, even when they match the other rules.
Parameters
values
...any[]
The values forbidden, compared by deep equality; references are resolved during the validation.
Returns
this
A new schema.
Inherited from
keep()
keep():
this
Keep the errors of the last rule (or ruleset) reported when it fails, even with the abortEarly option: same as rule({keep: true}). It ends the current ruleset: use rule() to set several rule options.
Returns
this
A new schema.
Inherited from
label()
label(
name):this
Set the name of the value in the error messages ({{#label}}), in place of its key.
Parameters
name
string
The label, a non-empty string.
Returns
this
A new schema.
Inherited from
message()
message(
message):this
Set the error message of the last rule (or ruleset): same as rule({message}). It ends the current ruleset: use rule() to set several rule options.
Parameters
message
string
The message template, like '{{#label}} is too short'.
Returns
this
A new schema.
Inherited from
messages()
messages(
messages):this
Set the error messages of the whole schema, by error code: same as prefs({messages}). Unlike message(), which applies to the last rule, it applies to every rule of the schema.
Parameters
messages
LanguageMessages
The message templates by error code ({'string.min': '…'}), or by language then error code.
Returns
this
A new schema.
Inherited from
meta()
meta(
meta):this
Attach metadata to the schema, an annotation shown by describe().
Parameters
meta
object
Any value other than undefined.
Returns
this
A new schema.
Inherited from
not()
not(...
values):this
Forbid values (an alias of invalid()).
Parameters
values
...any[]
The values forbidden, compared by deep equality.
Returns
this
A new schema.
Inherited from
note()
note(...
notes):this
Add notes to the schema, annotations shown by describe().
Parameters
notes
...string[]
The notes, non-empty strings.
Returns
this
A new schema.
Inherited from
only()
only():
this
Allow only the values given to allow(), turning them into valid() values. It has no effect after valid(), which already does.
Returns
this
A new schema.
Inherited from
optional()
optional():
this
Allow the value to be undefined. The values are optional by default: this undoes required(), or the presence validation option.
Returns
this
A new schema.
Inherited from
options()
options(
options):this
Set validation options for this schema and its children, overriding the options given to the validation (an alias of prefs()).
Parameters
options
The validation options.
Returns
this
A new schema.
Inherited from
preferences()
preferences(
options):this
Set validation options for this schema and its children, overriding the options given to the validation (an alias of prefs()).
Parameters
options
The validation options.
Returns
this
A new schema.
Inherited from
prefs()
prefs(
options):this
Set validation options for this schema and its children, overriding the options given to the validation.
Parameters
options
The validation options.
Returns
this
A new schema.
Inherited from
presence()
presence(
mode):this
Set the presence of the value: optional (the default), required or forbidden.
Parameters
mode
PresenceMode
The presence mode.
Returns
this
A new schema.
Inherited from
raw()
raw(
enabled?):this
Return the original value, as given, instead of the converted one once the validation passes.
Parameters
enabled?
boolean
Whether to return the original value. Defaults to true.
Returns
this
A new schema.
Inherited from
required()
required():
this
Require the value: undefined is not allowed. The values are optional by default.
Returns
this
A new schema.
Inherited from
rule()
rule(
options):this
Apply options to the last rule added (like min()), or to every rule of the current ruleset ($.min(1).max(9)). Once called, the previous rules can no longer be changed and the ruleset ends.
Parameters
options
RuleOptions
The rule options: its error message, keep, warn.
Returns
this
A new schema.
Throws
When the last rule does not support options: the flags (required(), valid(), …) do not; change their messages with messages().
Inherited from
sensitive()
sensitive(
enabled?):this
Compare the strings converted to booleans ('true', 'false', and the ones of truthy() and falsy()) case-sensitively.
Parameters
enabled?
boolean
Whether the comparison is case-sensitive. Defaults to true.
Returns
this
A new schema.
shared()
shared(
ref):this
Register a schema with an id, which the links (DTO.Link('#id')) of the descendants of this schema can reach.
Parameters
ref
The schema, which must have an id (id()).
Returns
this
A new schema.
Throws
When the schema has no id.
Inherited from
strict()
strict(
isStrict?):this
Set whether the values are converted to the type of the schema (the string '5' to a number, 'true' to a boolean), for this schema and its children. The schemas built by DTO start strict.
Parameters
isStrict?
boolean
True (the default) to disable the conversions, false to enable them.
Returns
this
A new schema.
Inherited from
strip()
strip(
enabled?):this
Remove the value from the validated object or array, after its validation. Used to sanitize an output.
Parameters
enabled?
boolean
Whether to remove the value. Defaults to true.
Returns
this
A new schema.
Inherited from
tag()
tag(...
tags):this
Add tags to the schema, annotations shown by describe().
Parameters
tags
...string[]
The tags, non-empty strings.
Returns
this
A new schema.
Inherited from
tailor()
tailor(
targets):Schema
Apply the alterations assigned by alter() to a copy of the schema, its children included.
Parameters
targets
string | string[]
The name of the alteration, or several names applied in order.
Returns
The altered copy.
Inherited from
truthy()
truthy(...
values):this
Accept other values as true, with conversion enabled (strict(false)). The strings are compared case-insensitively unless sensitive() is called.
Parameters
values
...(string | number | null)[]
The values converted to true: strings, numbers or null.
Returns
this
A new schema.
unit()
unit(
name):this
Set the unit of the value ('ms', 'bytes'), an annotation shown by describe().
Parameters
name
string
The unit, a non-empty string.
Returns
this
A new schema.
Inherited from
valid()
valid(...
values):this
Allow only the given values (DTO.String().valid('asc', 'desc')), in addition to the ones of allow().
Parameters
values
...any[]
The only values allowed, compared by deep equality; references are resolved during the validation.
Returns
this
A new schema.
Inherited from
warn()
warn():
this
Make the last rule (or ruleset) a warning, which does not fail the validation: same as rule({warn: true}). DTO.validate() does not report the warnings. It ends the current ruleset: use rule() to set several rule options.
Returns
this
A new schema.
Inherited from
warning()
warning(
code,context):this
Add a rule which always reports a warning, which does not fail the validation. DTO.validate() does not report the warnings.
Parameters
code
string
The error code of the warning, whose message is looked up like the error ones.
context
Context
The variables of the message.
Returns
this
A new schema.
Inherited from
when()
Call Signature
when(
ref,options):this
Apply another schema depending on the value of another key (or of the global context): the schema of a condition met is concatenated to this one.
Parameters
ref
string | Reference
The key the condition reads ('type', '..parent.key', '/root', '$context'), or a reference.
options
WhenOptions | WhenOptions[]
The condition: is (a schema or a value the referenced value must match), then the schema concatenated to this one when it does (then) or does not (otherwise); or a list of conditions, or a switch.
Returns
this
A new schema.
Example
import {DTO} from 'lakutata'
//The card number is required when the payment is by card
const schema = DTO.Object({
method: DTO.String().valid('card', 'cash').required(),
card: DTO.String().when('method', {is: 'card', then: DTO.Any().required(), otherwise: DTO.Any().forbidden()})
})Inherited from
Call Signature
when(
ref,options):this
Apply another schema depending on whether the value itself matches a schema.
Parameters
ref
The schema the value is tested against.
options
WhenSchemaOptions
The schema concatenated to this one when the value matches (then) or does not (otherwise).
Returns
this
A new schema.