Interface: ObjectSchema<TSchema>
A schema of objects, built by DTO.Object(keys) (and returned by DTO.Schema() for a DTO class): the schemas of its keys, the unknown keys, and the dependencies between keys.
The validations of lakutata allow the unknown keys and remove them from the validated object (the allowUnknown and stripUnknown options); unknown(false) rejects them instead.
Extends
AnySchema<TSchema>
Type Parameters
TSchema
TSchema = any
The type of the objects 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
and()
and(...
peers):this
Require all the keys together: when one of them is present, all of them must be.
Parameters
peers
...(string | DependencyOptions)[]
The key names (dotted paths reach nested keys), optionally followed by the options: separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
append()
Call Signature
append(
schema?):this
Add keys to the schema, replacing the schemas of the keys already present. Unlike keys(), an empty or missing argument changes nothing.
Parameters
schema?
PartialSchemaMap<TSchema>
The schemas of the keys to add, by key.
Returns
this
A new schema.
Call Signature
append<
TSchemaExtended,T>(schema?):ObjectSchema<T>
Type Parameters
TSchemaExtended
TSchemaExtended = any
T
T = TSchemaExtended
Parameters
schema?
PartialSchemaMap<T>
Returns
ObjectSchema<T>
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
assert()
assert(
ref,schema,message?):this
Require a value of the object to match a schema (the object itself fails, with the message).
Parameters
ref
string | Reference
The value tested: a key path relative to the object, which starts with . ('.a.b'), or a reference.
schema
The schema the value must match, like DTO.Ref('b') to require it to equal another key.
message?
string
The reason shown in the error message (… failed to <message>).
Returns
this
A new schema.
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
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
instance()
instance(
constructor,name?):this
Require the object to be an instance of a class.
Parameters
constructor
Function
The class the object must be an instance of.
name?
string
The name of the class in the error messages, for a class without a name. Defaults to its name.
Returns
this
A new schema.
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
keyNames()
keyNames(
schema):this
Require every key name of the object to match a schema.
Parameters
schema
The schema of the key names, like DTO.String().pattern(/^[a-z]+$/).
Returns
this
A new schema.
keys()
keys(
schema?):this
Set the keys of the schema, adding to the keys already set (a key given again replaces its schema). Without an argument, any key is allowed; with {}, no key is.
Parameters
schema?
PartialSchemaMap<TSchema>
The schemas of the keys, by key.
Returns
this
A new schema.
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
length()
length(
limit):this
Require an exact number of keys.
Parameters
limit
number
The number of keys.
Returns
this
A new schema.
max()
max(
limit):this
Require at most a number of keys.
Parameters
limit
number | Reference
The maximum number of keys (inclusive), or a reference to another value holding it.
Returns
this
A new schema.
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
min()
min(
limit):this
Require at least a number of keys.
Parameters
limit
number | Reference
The minimum number of keys (inclusive), or a reference to another value holding it.
Returns
this
A new schema.
nand()
nand(...
peers):this
Forbid all the keys together: some of them may be present, not all of them.
Parameters
peers
...(string | DependencyOptions)[]
The key names (dotted paths reach nested keys), optionally followed by the options: separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
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
or()
or(...
peers):this
Require at least one of the keys (several are allowed).
Parameters
peers
...(string | DependencyOptions)[]
The key names (dotted paths reach nested keys), optionally followed by the options: separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
oxor()
oxor(...
peers):this
Allow at most one of the keys: none or one of them.
Parameters
peers
...(string | DependencyOptions)[]
The key names (dotted paths reach nested keys), optionally followed by the options: separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
pattern()
pattern(
pattern,schema,options?):this
Specify validation rules for unknown keys matching a pattern.
Parameters
pattern
RegExp | SchemaLike
A regular expression, or a schema, the unknown key names are tested against.
schema
The schema of the values of the matching keys.
options?
ObjectPatternOptions
fallthrough: whether a key matching this pattern is also tested against the following patterns (default false); matches: a schema the array of the matching key names must match (like DTO.Array().max(3)).
Returns
this
A new schema.
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
ref()
ref():
this
Require the value to be a reference (created by DTO.Ref()).
Returns
this
A new schema.
regex()
regex():
this
Require the value to be a RegExp object.
Returns
this
A new schema.
rename()
rename(
from,to,options?):this
Rename a key of the validated object, before its keys are validated: the old key is removed unless the alias option is set.
Parameters
from
string | RegExp
The key to rename, or a regular expression matching the keys to rename.
to
string
The new key name.
options?
RenameOptions
alias (keep the old key too), multiple (allow several keys renamed to the same one, the last wins), override (allow replacing an existing key), ignoreUndefined (skip an undefined value); all false by default.
Returns
this
A new schema.
Throws
When the key is already renamed by the schema, or renamed to itself.
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
schema()
schema(
type?):this
Require the value to be a schema (built by DTO).
Parameters
type?
The type the schema must have ('number'). Defaults to any, which accepts every schema.
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
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
unknown()
unknown(
allow?):this
Set whether the unknown keys are allowed, for this object only (not its children), overriding the allowUnknown validation option. Allowed unknown keys are kept in the validated object.
Parameters
allow?
True (the default) to allow and keep them, false to reject them, or a schema their values must match.
Returns
this
A new schema.
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.
Inherited from
with()
with(
key,peers,options?):this
Require other keys whenever a key is present.
Parameters
key
string
The key (a dotted path reaches a nested key).
peers
string | string[]
The keys required with it.
options?
DependencyOptions
separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
without()
without(
key,peers,options?):this
Forbid other keys whenever a key is present.
Parameters
key
string
The key (a dotted path reaches a nested key).
peers
string | string[]
The keys forbidden with it.
options?
DependencyOptions
separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.
xor()
xor(...
peers):this
Require exactly one of the keys.
Parameters
peers
...(string | DependencyOptions)[]
The key names (dotted paths reach nested keys), optionally followed by the options: separator of the paths (default .), isPresent (what counts as present, by default not undefined).
Returns
this
A new schema.