Tuple

Tuple type

A tuple type represents an array field of a fixed length, and each element inside the array can have a specific type. You may create a tuple using the vine.tuple method and define the types for individual elements.

In the following example, we define a tuple that accepts the latitude and the longitude pair. The validation will fail if the provided array has less than two properties or if any field is not a number.

import vine from '@vinejs/vine'
const schema = vine.object({
coordinates: vine.tuple([
vine.number(),
vine.number(),
])
})

Using the following modifiers, you may mark the field as optional or nullable.

See also: Working with undefined and null values

{
coordinates: vine.tuple([
vine.number(),
vine.number(),
])
.nullable()
}
{
coordinates: vine.tuple([
vine.number(),
vine.number(),
])
.optional()
}

Allowing unknown properties

By default, the tuple keeps only the validated properties in the output, and the rest of the array elements are ignored. However, if needed, you may copy the rest of the properties using the allowUnknownProperties method.

import vine from '@vinejs/vine'
const schema = vine.object({
top_scores: vine.tuple([
vine.number(),
vine.number(),
vine.number(),
])
})
const data = {
top_scores: [
98,
96,
92,
88,
84
]
}
const validate = vine.compile(schema)
const output = await validate(data)
/*
const data = {
topScores: [
98,
96,
92,
]
}
*/

Defining error message

You may define the custom error message using the tuple rule name.

const messages = {
tuple: 'The {{ field }} field must be an array'
}
vine.messagesProvider = new SimpleMessagesProvider(messages)