API Reference
Complete API documentation for valrs
API Reference
This section provides complete documentation for all valrs exports.
The v Namespace
The v namespace is the primary API for valrs, providing a Zod-compatible fluent interface for schema definition and validation.
Initialization
init()
Initialize the WebAssembly module. Must be called before using any validation functions.
Returns: Promise<void>
Note: In Node.js, this uses a JavaScript fallback and returns immediately. In browsers, the WASM binary is loaded asynchronously.
isInitialized()
Check if the WASM module has been initialized.
Returns: boolean
Primitive Schemas
v.string()
Creates a schema for string values with validation and transformation methods.
Returns: ValString
String Methods
| Method | Description |
|---|---|
.min(length, message?) | Minimum length |
.max(length, message?) | Maximum length |
.length(length, message?) | Exact length |
.email(message?) | Valid email format |
.url(message?) | Valid URL format |
.uuid(message?) | Valid UUID v4 format |
.cuid(message?) | Valid CUID format |
.cuid2(message?) | Valid CUID2 format |
.ulid(message?) | Valid ULID format |
.datetime(message?) | Valid ISO 8601 datetime |
.ip(message?) | Valid IPv4 or IPv6 |
.regex(pattern, message?) | Match regex pattern |
.includes(substring, message?) | Contains substring |
.startsWith(prefix, message?) | Starts with prefix |
.endsWith(suffix, message?) | Ends with suffix |
.trim() | Trim whitespace (transform) |
.toLowerCase() | Convert to lowercase (transform) |
.toUpperCase() | Convert to uppercase (transform) |
v.number()
Creates a schema for number values (IEEE 754 double-precision).
Returns: ValNumber
Number Methods
| Method | Description |
|---|---|
.min(value, message?) | Minimum value (inclusive) |
.max(value, message?) | Maximum value (inclusive) |
.gt(value, message?) | Greater than |
.gte(value, message?) | Greater than or equal |
.lt(value, message?) | Less than |
.lte(value, message?) | Less than or equal |
.int(message?) | Must be integer |
.positive(message?) | Must be positive |
.nonnegative(message?) | Must be non-negative |
.negative(message?) | Must be negative |
.nonpositive(message?) | Must be non-positive |
.multipleOf(value, message?) | Must be divisible by value |
.finite(message?) | Must be finite |
.safe(message?) | Must be safe integer |
v.bigint()
Creates a schema for BigInt values.
Returns: ValBigInt
BigInt Methods
| Method | Description |
|---|---|
.min(value, message?) | Minimum value |
.max(value, message?) | Maximum value |
.positive(message?) | Must be positive |
.nonnegative(message?) | Must be non-negative |
.negative(message?) | Must be negative |
.nonpositive(message?) | Must be non-positive |
v.boolean()
Creates a schema for boolean values.
Returns: ValBoolean
v.date()
Creates a schema for Date objects.
Returns: ValDate
Date Methods
| Method | Description |
|---|---|
.min(date, message?) | Minimum date |
.max(date, message?) | Maximum date |
v.null()
Creates a schema that only accepts null.
Returns: ValNull
v.undefined()
Creates a schema that only accepts undefined.
Returns: ValUndefined
v.void()
Creates a schema that accepts undefined (alias for undefined, for function return types).
Returns: ValVoid
v.any()
Creates a schema that accepts any value. Use sparingly.
Returns: ValAny
v.unknown()
Creates a schema that accepts any value but requires type narrowing before use.
Returns: ValUnknown
v.never()
Creates a schema that never matches any value. Useful for exhaustive type checking.
Returns: ValNever
Constructor Schemas
v.object()
Creates an object schema from a shape definition.
Returns: ValObject<T>
Object Methods
| Method | Description |
|---|---|
.extend(shape) | Add additional properties |
.merge(schema) | Merge with another object schema |
.pick(keys) | Select specific properties |
.omit(keys) | Exclude specific properties |
.partial() | Make all properties optional |
.deepPartial() | Make all properties optional recursively |
.required() | Make all properties required |
.passthrough() | Allow unknown properties |
.strict() | Reject unknown properties |
.strip() | Remove unknown properties |
.catchall(schema) | Validate unknown properties with schema |
.keyof() | Get enum of keys |
v.array()
Creates an array schema for the given element type.
Returns: ValArray<S>
Array Methods
| Method | Description |
|---|---|
.min(length, message?) | Minimum array length |
.max(length, message?) | Maximum array length |
.length(length, message?) | Exact array length |
.nonempty(message?) | Array must have at least one item |
.element | Access the element schema |
v.tuple()
Creates a tuple schema with fixed element types.
Returns: ValTuple<T>
Tuple Methods
| Method | Description |
|---|---|
.rest(schema) | Allow additional elements of type |
v.record()
Creates a record schema (object with string keys and typed values).
Signatures:
v.record(valueSchema)- String keys with typed valuesv.record(keySchema, valueSchema)- Typed keys and values
Returns: ValRecord<K, V>
v.map()
Creates a schema for JavaScript Map objects.
Returns: ValMap<K, V>
v.set()
Creates a schema for JavaScript Set objects.
Returns: ValSet<V>
v.union()
Creates a union schema (one of multiple types).
Returns: ValUnion<T>
v.discriminatedUnion()
Creates a discriminated union schema (tagged union) for efficient matching.
Returns: ValDiscriminatedUnion<D, T>
v.intersection()
Creates an intersection schema (all types must match).
Returns: ValIntersection<L, R>
v.literal()
Creates a schema for a single literal value.
Returns: ValLiteralValue<T>
v.enum()
Creates an enum schema for a fixed set of string values.
Returns: ValEnum<T>
v.nativeEnum()
Creates a schema for TypeScript native enums.
Returns: ValNativeEnum<T>
Utility Functions
v.preprocess()
Preprocesses input before passing to the schema.
Parameters:
preprocessFn: (value: unknown) => Input- Transform functionschema: ValSchema<Input, Output>- Schema to validate after preprocessing
Returns: ValPreprocessed<Input, Output>
v.coerce
Coercion schema builders that attempt to convert input values to the target type before validation.
| Method | Description |
|---|---|
v.coerce.string() | Coerce to string using String() |
v.coerce.number() | Coerce to number using Number() (fails if NaN) |
v.coerce.boolean() | Coerce to boolean using Boolean() |
v.coerce.bigint() | Coerce to bigint using BigInt() |
v.coerce.date() | Coerce to Date using new Date() |
Streaming Validation
v.stream()
Streams and validates a JSON array with O(1) memory usage.
Parameters:
schema: ValArray<S>- Array schema to validateinput: StreamInput- ReadableStream, Response, string, or async iterableoptions?: StreamOptions- Optional streaming configuration
Returns: StreamResult<T> or StreamResultWithErrors<T>
StreamOptions
| Option | Type | Description |
|---|---|---|
maxItems | number | Maximum items to process |
maxBytes | number | string | Maximum bytes (e.g., '100MB') |
timeout | number | string | Timeout duration (e.g., '30s') |
onError | 'throw' | 'skip' | 'collect' | Error handling strategy |
highWaterMark | number | Backpressure threshold (default: 16) |
v.streamLines()
Streams and validates NDJSON (newline-delimited JSON) data.
Parameters:
schema: ValSchema<unknown, T>- Schema for each lineinput: StreamInput- Input streamoptions?: StreamOptions- Optional streaming configuration
Returns: StreamResult<T>
ValError Class
Error thrown when schema.parse() fails. Contains detailed information about all validation issues.
Properties
| Property | Type | Description |
|---|---|---|
issues | ReadonlyArray<ValIssue> | All validation issues |
message | string | Formatted error message |
name | 'ValError' | Error name |
firstError | ValIssue | undefined | First issue, if any |
Methods
format()
Formats errors as a nested object matching the path structure.
Returns: FormattedError<T>
flatten()
Flattens issues into a simple object with form errors and field errors.
Returns: FlattenedError<T>
hasErrorAt(path)
Checks if there are errors at the specified path.
Parameters:
path: ReadonlyArray<string | number>- Path to check
Returns: boolean
errorsAt(path)
Gets all errors at the specified path.
Parameters:
path: ReadonlyArray<string | number>- Path to check
Returns: ReadonlyArray<ValIssue>
addIssue(issue)
Returns a new ValError with an additional issue.
Returns: ValError
addIssues(issues)
Returns a new ValError with additional issues.
Returns: ValError
Static Methods
ValError.isValError(value)
Type guard to check if a value is a ValError instance.
Returns: value is ValError
ValError.fromValIssues(issues)
Creates a ValError directly from ValIssue array.
Returns: ValError
Issue Codes
All possible Zod-compatible validation error codes:
| Code | Description |
|---|---|
invalid_type | Type mismatch |
invalid_literal | Literal value mismatch |
custom | Custom validation error |
invalid_union | No union variant matched |
invalid_union_discriminator | Invalid discriminator value |
invalid_enum_value | Invalid enum value |
unrecognized_keys | Unknown object keys |
invalid_arguments | Invalid function arguments |
invalid_return_type | Invalid function return |
invalid_date | Invalid Date |
invalid_string | String format validation failed |
too_small | Value too small |
too_big | Value too big |
invalid_intersection_types | Intersection type mismatch |
not_multiple_of | Not a multiple of value |
not_finite | Not a finite number |
Error Map
Customize error messages globally or per-validation.
setErrorMap()
Sets a global error map for all validations.
getErrorMap()
Gets the current global error map.
resetErrorMap()
Resets the global error map to undefined.
Schema Methods
All schemas inherit these methods from ValSchema:
parse(value)
Validates and returns the value, throwing ValError on failure.
safeParse(value)
Validates and returns a result object (never throws).
Returns: SafeParseResult<T>
optional()
Makes the schema accept undefined.
nullable()
Makes the schema accept null.
nullish()
Makes the schema accept null or undefined.
default(value)
Provides a default value for undefined inputs.
catch(value)
Provides a fallback value on validation failure.
transform(fn)
Transforms the validated value.
refine(fn, message?)
Adds a custom validation predicate.
superRefine(fn)
Adds a custom validation with full context access.
pipe(schema)
Chains another schema after this one.
Type Inference
v.infer<T>
Infers the output type from a schema.
v.input<T>
Infers the input type from a schema (useful when input differs from output).
v.output<T>
Infers the output type from a schema (alias for v.infer).
Types
See Types Reference for complete type definitions.