Interface: StringSchema<TSchema>
A schema of strings, built by DTO.String() (and DTO.Glob(), DTO.Cron(), DTO.HttpDocument()): length, patterns, formats (email, URI, UUID…) and case.
The empty string is rejected unless allowed (allow('')). The rules changing the string (trim(), lowercase(), uppercase(), case(), normalize(), replace(), truncate()) only change it with conversion enabled (strict(false)): the schemas built by DTO are strict, so these rules only check the string.
Extends
AnySchema<TSchema>
Type Parameters
TSchema
TSchema = string
The type of the strings 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
alphanum()
alphanum():
this
Require the string to only contain the characters a-z, A-Z and 0-9.
Returns
this
A new schema.
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
base64()
base64(
options?):this
Require the string to be valid base64; the decoded value is not checked.
Parameters
options?
Base64Options
paddingRequired: whether the = padding is required (default true); urlSafe: whether the URL-safe alphabet (- and _) is used instead of + and / (default false).
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
case()
case(
direction):this
Require the string to be all upper case or all lower case; with conversion enabled (strict(false)), it is converted instead.
Parameters
direction
"upper" | "lower"
The case required.
Returns
this
A new schema.
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
creditCard()
creditCard():
this
Require the string to be a credit card number (digits passing the Luhn checksum).
Returns
this
A new schema.
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
dataUri()
dataUri(
options?):this
Require the string to be a data URI (data:<media type>;base64,<data>).
Parameters
options?
DataUriOptions
paddingRequired: whether the base64 data requires its = padding (default true).
Returns
this
A new schema.
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
domain()
domain(
options?):this
Require the string to be a domain name, like example.com.
Parameters
options?
DomainOptions
The domain rules: minDomainSegments (default 2), maxDomainSegments, tlds (the allowed and denied top-level domains, the IANA list by default; false allows any), allowFullyQualified (a trailing ., default false), allowUnicode (default true).
Returns
this
A new schema.
email()
email(
options?):this
Require the string to be an email address. Its domain must have at least 2 segments and, by default, a top-level domain of the IANA list.
Parameters
options?
EmailOptions
The address rules: multiple (a list of addresses split by separator, default ,), tlds (the allowed and denied top-level domains; false allows any), minDomainSegments, maxDomainSegments, allowUnicode (default true), ignoreLength, allowFullyQualified.
Returns
this
A new schema.
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
format()
format(
name):this
Require the string to be valid in a JSON Schema format, checked like the full formats of ajv-formats.
Parameters
name
string
The format: date, time, date-time, duration, email, idn-email, hostname, ipv4, ipv6, uri, uri-reference, uri-template, uuid, regex, json-pointer, relative-json-pointer or byte (base64).
Returns
this
A new schema.
Throws
When the format is not one of these.
guid()
guid(
options?):this
Require the string to be a GUID (a UUID), optionally wrapped in {}, () or [].
Parameters
options?
GuidOptions
version: the UUID versions allowed ('uuidv4', or a list), any by default; separator: the separator required between the groups (- or :), true for either, false for none; optional by default.
Returns
this
A new schema.
hex()
hex(
options?):this
Require the string to be hexadecimal.
Parameters
options?
HexOptions
byteAligned: whether the length must be even (default false); prefix: whether the 0x prefix is required (true), forbidden (false, the default) or allowed ('optional').
Returns
this
A new schema.
hostname()
hostname():
this
Require the string to be a host name (RFC 1123), or an IP address.
Returns
this
A new schema.
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
insensitive()
insensitive():
this
Compare the string with the values of valid(), allow() and invalid() case-insensitively.
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
ip()
ip(
options?):this
Require the string to be an IP address.
Parameters
options?
IpOptions
version: the versions allowed ('ipv4', 'ipv6', 'ipvfuture', or a list), all by default; cidr: whether a CIDR suffix (/24) is optional (the default), required or forbidden.
Returns
this
A new schema.
isoDate()
isoDate():
this
Require the string to be an ISO 8601 date (2024-01-31, 2024-01-31T12:00:00Z); with conversion enabled (strict(false)), it is converted to the full ISO format (2024-01-31T00:00:00.000Z).
Returns
this
A new schema.
isoDuration()
isoDuration():
this
Require the string to be an ISO 8601 duration, like P1DT2H.
Returns
this
A new schema.
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
length()
length(
limit,encoding?):this
Require an exact length.
Parameters
limit
number | Reference
The length, in characters (UTF-16 code units), or a reference to another value holding it.
encoding?
string
An encoding ('utf8'): the length is then counted in bytes in that encoding.
Returns
this
A new schema.
lowercase()
lowercase():
this
Require the string to be all lower case; with conversion enabled (strict(false)), it is converted instead.
Returns
this
A new schema.
max()
max(
limit,encoding?):this
Require a maximum length (see truncate() to cut longer strings instead).
Parameters
limit
number | Reference
The maximum length (inclusive), in characters (UTF-16 code units), or a reference to another value holding it.
encoding?
string
An encoding ('utf8'): the length is then counted in bytes in that encoding.
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,encoding?):this
Require a minimum length.
Parameters
limit
number | Reference
The minimum length (inclusive), in characters (UTF-16 code units), or a reference to another value holding it.
encoding?
string
An encoding ('utf8'): the length is then counted in bytes in that encoding.
Returns
this
A new schema.
normalize()
normalize(
form?):this
Require the string to be in a Unicode normalization form; with conversion enabled (strict(false)), it is normalized instead.
Parameters
form?
"NFC" | "NFD" | "NFKC" | "NFKD"
The normalization form. Defaults to NFC.
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
pattern()
pattern(
pattern,options?):this
Require the string to match a regular expression.
Parameters
pattern
RegExp
The regular expression (its g and y flags are not allowed).
options?
string | StringRegexOptions
The name of the pattern in the error messages, or an object: name, and invert (true: the string must not match; default false).
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
regex()
regex(
pattern,options?):this
Require the string to match a regular expression (an alias of pattern()).
Parameters
pattern
RegExp
The regular expression (its g and y flags are not allowed).
options?
string | StringRegexOptions
The name of the pattern in the error messages, or an object: name, and invert (true: the string must not match; default false).
Returns
this
A new schema.
replace()
replace(
pattern,replacement):this
Replace the parts of the string matching a pattern, before the other rules; only with conversion enabled (strict(false)), otherwise the rule does nothing.
Parameters
pattern
string | RegExp
A regular expression (add its g flag to replace every match), or a string whose occurrences are all replaced.
replacement
string
The replacement, which may use the groups of a regular expression ($1).
Returns
this
A new schema.
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
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
token()
token():
this
Require the string to only contain the characters a-z, A-Z, 0-9 and _.
Returns
this
A new schema.
trim()
trim(
enabled?):this
Require the string to have no leading or trailing whitespace; with conversion enabled (strict(false)), it is trimmed instead.
Parameters
enabled?
any
Whether the rule applies: a falsy value removes it. Defaults to true.
Returns
this
A new schema.
truncate()
truncate(
enabled?):this
Cut the strings longer than the max() limit to it, instead of rejecting them; only with conversion enabled (strict(false)).
Parameters
enabled?
boolean
Whether to truncate: false restores the rejection. Defaults to true.
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
uppercase()
uppercase():
this
Require the string to be all upper case; with conversion enabled (strict(false)), it is converted instead.
Returns
this
A new schema.
uri()
uri(
options?):this
Require the string to be a URI (RFC 3986), absolute by default.
Parameters
options?
UriOptions
scheme: the schemes allowed ('https', a regular expression, or a list), any by default; allowRelative: whether relative URIs are allowed too (default false); relativeOnly: whether only relative URIs are (default false); allowQuerySquareBrackets (default false); domain: the rules of the host name, as in domain().
Returns
this
A new schema.
uuid()
uuid(
options?):this
Require the string to be a UUID (an alias of guid()).
Parameters
options?
GuidOptions
version: the UUID versions allowed ('uuidv4', or a list), any by default; separator: the separator required between the groups (- or :), true for either, false for none; optional by default.
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.