ProtectedconstructorReadonly Internal[___Type-level brand encoding whether this schema has a default value. Not emitted at runtime — used by input type inference.
Readonly Internal[___Type-level brand encoding the inferred type of this schema. Not emitted at runtime — used only by InferType.
Standard Schema v1 interface.
Exposes this schema as a Standard Schema v1 validator, enabling out-of-the-box interoperability with any library that consumes the spec — including tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, next-safe-action, and 50+ other tools.
Every SchemaBuilder subclass (all 13 builders) inherits this property
automatically — no additional setup required.
Shape of the returned object:
version — always 1 (Standard Schema spec version)vendor — '@cleverbrush/schema'validate(value) — synchronous; wraps this builder's own .validate()
and converts its result to the Standard Schema Result<Output> format:
{ value: <validated output> }{ issues: [{ message: string }, …] }The returned object is cached after the first access so repeated reads return the same reference (required by the spec).
import { object, string, number } from '@cleverbrush/schema';
const UserSchema = object({
name: string().minLength(2),
email: string().email(),
age: number().min(18).optional(),
});
// Grab the Standard Schema interface
const std = UserSchema['~standard'];
// std.version === 1
// std.vendor === '@cleverbrush/schema'
const ok = std.validate({ name: 'Alice', email: 'alice@example.com' });
// { value: { name: 'Alice', email: 'alice@example.com', age: undefined } }
const fail = std.validate({ name: 'A', email: 'not-an-email' });
// { issues: [{ message: 'minLength' }, { message: 'email' }] }
// Pass directly to TanStack Form, T3 Env, tRPC, etc.:
// validators: { onChange: UserSchema, onBlur: UserSchema }
ProtectedcanWhether preValidateSync can be skipped entirely.
True when there are no preprocessors and no validators,
so the only work would be the required check and wrapping
in a noop transaction — which subclasses can do inline.
ProtectedhasWhether this schema has a catch/fallback value configured via .catch().
ProtectedhasWhether this schema has a default value configured via .default().
Exposed for fast-path validation in subclasses.
ProtectedisWhether null is an accepted value for this schema.
ProtectedisProtectedWhether null should count as a required-constraint violation.
By default null is treated the same as undefined for the purposes
of the required check — i.e. a required schema rejects both.
Subclasses that may legally receive null as a value (e.g.
UnionSchemaBuilder when a NullSchemaBuilder option is present)
can override this to false so that null bypasses the required
check and is passed directly to their option-validation logic.
ProtectedisWhether this schema is marked as readonly. Type-level only — no runtime enforcement.
ProtectedisWhether the schema requires a non-null/non-undefined value.
Sets the requirement flag. Must be a boolean.
ProtectedpreprocessorsA list of preprocessors associated with the Builder
ProtectedrequiredThe error message provider used for the "is required" error. Exposed for fast-path validation in subclasses.
ProtectedtypeThe string identifier of the schema type (e.g. 'string', 'number', 'object').
Sets the schema type identifier. Must be a non-empty string.
ProtectedvalidatorsA list of validators associated with the Builder
Protected_Performs synchronous validation of the schema over object.
Throws if any preprocessor, validator, or error message provider returns a Promise.
Optionalcontext: ValidationContextOptional ValidationContext settings.
Protected_Performs async validation of the schema over object.
Supports async preprocessors, validators, and error message providers.
Optionalcontext: ValidationContextOptional ValidationContext settings.
Adds a preprocessor to a preprocessors list
Optionaloptions: { mutates?: boolean }Adds a validator to validators list.
Optionaloptions: { mutates?: boolean }ProtectedassureEnsures a ValidationErrorMessageProvider is valid.
If provider is undefined, falls back to defaultValue.
Function providers are bound to this for access to schema state.
the provider to validate, or undefined
fallback provider when provider is not supplied
a valid ValidationErrorMessageProvider
Sets a fallback value for this schema. When validation fails for any reason, the fallback value is returned as a successful result instead of validation errors.
This is useful for graceful degradation — for example, providing a safe default when parsing untrusted input that might not conform to the schema.
Accepts either a static value or a factory function. Factory functions are called
each time the fallback is needed (useful for mutable values like () => []).
Unlike default, which only fires when the input is undefined, .catch()
fires on any validation failure — type mismatch, constraint violation, etc.
When .catch() is set, parse and parseAsync will never throw.
const schema = string().catch('unknown');
schema.validate(42); // { valid: true, object: 'unknown' }
schema.validate('hello'); // { valid: true, object: 'hello' }
schema.parse(42); // 'unknown' (no throw)
// Factory function for mutable fallbacks
const schema = array(string()).catch(() => []);
schema.validate(null); // { valid: true, object: [] }
// Contrast with .default() — default fires only on undefined
const d = string().default('anon');
d.validate(undefined); // { valid: true, object: 'anon' } ← fires
d.validate(42); // { valid: false, errors: [...] } ← does NOT fire
const c = string().catch('anon');
c.validate(undefined); // { valid: true, object: 'anon' } ← fires
c.validate(42); // { valid: true, object: 'anon' } ← also fires
Clears type set by call to .hasType<T>(), default schema type inference will be used
for schema returned by this call.
Remove all preprocessors for this schema.
Removes the rest schema set by rest(). After this call, the tuple
length must be exactly equal to the number of fixed element schemas.
Remove all validators for this schema.
Attaches a human-readable description to this schema as runtime metadata.
The description has no effect on validation — it is purely informational.
It is accessible via .introspect().description and is emitted as the
description field by toJsonSchema() from @cleverbrush/schema-json.
Useful for documentation generation, form labels, and AI tool descriptions.
InternalRetrieves extension metadata by key.
Used by extension authors inside defineExtension() callbacks.
ProtectedgetResolves a ValidationErrorMessageProvider to a string error message.
Handles both string providers and function providers (sync or async).
the error message provider (string or function)
the value that caused the validation error
the resolved error message string
ProtectedgetSynchronously resolves a ValidationErrorMessageProvider to a string.
Throws if the provider function returns a Promise.
the error message provider (string or sync function)
the value that caused the validation error
the resolved error message string
Error if the provider returns a Promise (use getValidationErrorMessage with validateAsync)
Set type of schema explicitly. notUsed param is needed only for case when JS is used. E.g. when you
can't call method like schema.hasType<Date>(), so instead you can call schema.hasType(new Date())
with the same result.
Optional_notUsed: TGenerates a serializable object describing the defined schema
The catch/fallback value or factory function set via .catch().
The default value or factory function.
The human-readable description attached to this schema via .describe(),
or undefined if none was set.
Per-position element schemas defining the fixed tuple structure.
Extension metadata. Stores custom state set by schema extensions.
Whether a catch/fallback value has been set on this schema via .catch().
Whether a default value (or factory) has been set on this schema.
If set to true, schema values of null are considered valid.
If set to true, the inferred type is marked as readonly.
Type-level only — no runtime enforcement.
If set to false, schema will be optional (null or undefined values
will be considered as valid).
Array of preprocessor functions
Custom error message provider for the 'is required' validation error.
Optional schema for elements beyond the fixed positions.
When set, additional elements are validated against this schema.
Mirrors TypeScript's rest element syntax: [string, number, ...boolean[]].
String id of schema type, e.g. string', numberorobject`.
Array of validator functions
Synchronously validates the value and returns it if valid. Throws a SchemaValidationError if validation fails.
the value to parse
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>optional validation context
the validated value
Asynchronously validates the value and returns it if valid. Throws a SchemaValidationError if validation fails.
the value to parse
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>optional validation context
the validated value
ProtectedpreOptionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>Use preValidateAsync instead. This alias will be removed in a future version.
ProtectedpreAsync version of pre-validation. Runs preprocessors, validators, and the
required/optional check on object. Supports async preprocessors,
validators, and error message providers.
the value to pre-validate
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>optional validation context settings
a PreValidationResult containing the preprocessed transaction, context, and any errors
ProtectedpreSynchronous version of preValidateAsync. Throws at runtime if any preprocessor or validator returns a Promise.
the value to pre-validate
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>optional validation context settings
a PreValidationResult containing the preprocessed transaction, context, and any errors
Error if a preprocessor or validator returns a Promise (use preValidateAsync instead)
Marks the inferred type as readonly. For objects, produces Readonly<T>.
For arrays, produces ReadonlyArray<T>. Primitives are unchanged.
Type-level only — no runtime enforcement.
ProtectedresolveResolves the catch/fallback value. If the stored value is a factory function,
it is called to produce the value (useful for mutable fallbacks like () => []).
ProtectedresolveResolves the default value. If the stored default is a function, it is called to produce the value (useful for mutable defaults).
Sets a schema that all elements beyond the fixed positions must satisfy.
Mirrors TypeScript's variadic tuple tail: [string, number, ...boolean[]].
When set, the tuple length must be at least equal to the number of fixed
elements, and any additional elements are validated against schema.
When not set, the tuple length must be exactly equal to the fixed count.
Schema that extra array elements must satisfy.
const schema = tuple([string(), number()]).rest(boolean());
// Inferred TypeScript type: [string, number, ...boolean[]]
schema.validate(['hello', 42]); // valid
schema.validate(['hello', 42, true]); // valid
schema.validate(['hello', 42, true, false]); // valid
schema.validate(['hello', 42, 'extra']); // invalid — 'extra' not boolean
Alias for validate. Synchronously validates and returns a result object. Provided for familiarity with the zod API.
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>Alias for validateAsync. Asynchronously validates and returns a result object. Provided for familiarity with the zod API.
Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>Perform synchronous schema validation on object.
Throws at runtime if any preprocessor, validator, or error message
provider returns a Promise — use validateAsync instead.
If a fallback has been set via catch, a failed validation result
is replaced by a successful result built from the fallback value, preserving
the specialized result shape (e.g. getErrorsFor / getNestedErrors methods).
Object to validate
Optionalcontext: ValidationContextOptional ValidationContext settings
Perform asynchronous schema validation on object.
Supports async preprocessors, validators, and error message providers.
If a fallback has been set via catch, a failed validation result
is replaced by a successful result built from the fallback value, preserving
the specialized result shape (e.g. getErrorsFor / getNestedErrors methods).
Object to validate
Optionalcontext: ValidationContextOptional ValidationContext settings
InternalSets extension metadata by key. Returns a new schema instance with the
extension data stored. The data survives fluent chaining.
Used by extension authors inside defineExtension() callbacks.
Fixed-length array schema builder with per-position type validation. Similar to TypeScript's tuple types — each element at a specific array index is validated against its own schema.
Use it when you need to validate function arguments, CSV rows, coordinate pairs, structured event payloads, or any other fixed-structure array.
NOTE this class is exported only to give opportunity to extend it by inheriting. It is not recommended to create an instance of this class directly. Use tuple() function instead.
Example
Example
Example
See
tuple