Collections
Array, tuple, record, map, and set type schemas
Collections
valrs provides schemas for JavaScript collection types with chainable validation methods.
Arrays
Create array schemas with v.array():
Array Methods
| Method | Description |
|---|---|
.min(n) | Minimum number of elements |
.max(n) | Maximum number of elements |
.length(n) | Exact number of elements |
.nonempty() | At least one element (alias for .min(1)) |
.element | Access the element schema |
Array Examples
Type Inference
Tuples
Create tuple schemas with fixed element types using v.tuple():
Tuple with Rest Elements
Use .rest() to allow additional elements of a specific type:
Tuple Type Inference
Accessing Tuple Items
Records
Create record (dictionary) schemas with v.record():
Record with Key Validation
The first argument specifies the key schema (must be a string schema):
Record Type Inference
Maps
Create JavaScript Map schemas with v.map():
Map with Complex Types
Map Type Inference
JSON Schema Representation
Maps are represented as arrays of [key, value] tuples in JSON Schema since JSON doesn't support Map natively:
Sets
Create JavaScript Set schemas with v.set():
Set with Validated Elements
Set Type Inference
JSON Schema Representation
Sets are represented as arrays with uniqueItems: true in JSON Schema:
Nested Collections
Collections can be nested to create complex data structures:
Custom Error Messages
Pass custom error messages to collection validators:
Next Steps
- Objects - Object schemas and methods
- Unions - Union types and enums
- Custom Schemas - Creating custom validation logic