length
Creates a length validation action.
const Action = v.length<TInput, TRequirement, TMessage>(requirement, message);
Generics
TInputextends LengthInputTRequirementextends numberTMessageextends ErrorMessage<LengthIssue<TInput, TRequirement>> | undefined
Parameters
requirementTRequirementmessageTMessage
Explanation
With length you can validate the length of a string or array. For strings, length is measured like JavaScript's value.length, i.e. by UTF-16 code units. For arrays, length is measured by the number of items. If the input does not match the requirement, you can use message to customize the error message.
If you need to validate the number of user-perceived characters, use
graphemesinstead. If you need to count each Unicode code point as a single character (a supplementary code point occupies two UTF-16 code units in JavaScript), usecodePointsinstead.
Returns
ActionLengthAction<TInput, TRequirement, TMessage>
Examples
The following examples show how length can be used.
String schema
Schema to validate a string with a length of 8 UTF-16 code units.
const StringSchema = v.pipe(
v.string(),
v.length(8, 'The string must be 8 UTF-16 code units long.')
);
Array schema
Schema to validate the length of an array.
const ArraySchema = v.pipe(
v.array(v.number()),
v.length(100, 'The array must contain 100 numbers.')
);
Related
The following APIs can be combined with length.
Schemas
any, array, custom, instance, string, tuple, unknown
Methods
Actions
Utils
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/length/