Arrays
您好!Valibot 提供了 array 和 tuple 两种模式来验证数组。当数组包含任意数量的统一项目时,使用 array;而当数组具有特定形状时,则使用 tuple。
Array 模式
array 模式的第一个参数是一个模式,用于验证数组中的所有项目。
import * as v from 'valibot';
const ArraySchema = v.array(v.number()); // number[]
管道验证
您可以使用管道来验证数组的长度或内容。
import * as v from 'valibot';
const ArraySchema = v.pipe(
v.array(v.string()),
v.minLength(1),
v.maxLength(5),
v.includes('foo'),
v.excludes('bar')
);
Tuple 模式
tuple 模式用于验证具有特定形状的数组。传递给函数的第一个参数是一个模式元组,它定义了该数组的形状。
import * as v from 'valibot';
const TupleSchema = v.tuple([v.string(), v.number()]); // [string, number]
松散与严格元组
默认的 tuple 模式会移除未知的项目。这意味着你没有在第一个参数中定义的项目不会被验证,也不会被添加到输出中。您可以使用 looseTuple 或 strictTuple 模式来改变这种行为。
looseTuple模式允许未知项目并将其添加到输出中。strictTuple模式禁止未知项目,并对发现的第一个未知项目返回一个问题。
带有特定其余项目的元组
或者,您也可以使用 tupleWithRest 模式为未知项目定义一个特定模式。任何未在第一个参数中定义的项目都会根据第二个参数的模式进行验证。
import * as v from 'valibot';
const TupleSchema = v.tupleWithRest([v.string(), v.number()], v.null());
管道验证
与数组类似,您可以使用管道来验证元组的长度和内容。
import * as v from 'valibot';
const TupleSchema = v.pipe(
v.tupleWithRest([v.string()], v.string()),
v.maxLength(5),
v.includes('foo'),
v.excludes('bar')
);