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 Date schema over object.
Throws if any preprocessor, validator, or error message provider returns a Promise.
Optionalcontext: ValidationContextOptional ValidationContext settings.
Protected_Performs async validation of Date schema over object.
Supports async preprocessors, validators, and error message providers.
Optionalcontext: ValidationContextOptional ValidationContext settings.
Accepts epoch number as a valid Date.
Epoch number will be parsed using new Date(epoch).
Accepts JSON string as a valid Date.
String must be in ISO format and will be parsed using JSON.parse().
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 equals() call.
Clears type set by call to .hasType<T>(), default schema type inference will be used
for schema returned by this call.
Cancel isInFuture() call.
Cancel isInPast() call.
Clear max() call.
Clear min() call.
Remove all preprocessors for this schema.
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.
Cancel acceptEpoch() call.
Cancel acceptJsonString() call.
Restricts Date to be equal to value.
OptionalerrorMessage: ValidationErrorMessageProvider<Custom error message provider.
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.
Make sure that date is in future. false by default.
Ensure in future validation error message provider. If not provided, default error message will be used.
Make sure that date is in past. false by default.
Ensure in past validation error message provider. If not provided, default error message will be used.
If set, restrict date to be equal to a certain value.
Equals to validation error message provider. If not provided, default error message will be used.
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).
Max valid value (if defined).
Max value validation error message provider. If not provided, default error message will be used.
Min valid value (if defined).
Min value validation error message provider. If not provided, default error message will be used.
If set, schema will try to parse date from the UNIX epoch (number).
false by default.
If set, schema will try to parse date from JSON string.
false by default.
Array of preprocessor functions
Custom error message provider for the 'is required' validation error.
String id of schema type, e.g. string', numberorobject`.
Array of validator functions
Accept only dates in the future.
OptionalerrorMessage: ValidationErrorMessageProvider<Custom error message provider.
Accept only dates in the past.
OptionalerrorMessage: ValidationErrorMessageProvider<Custom error message provider.
Set maximal valid Date value for schema.
OptionalerrorMessage: ValidationErrorMessageProvider<Custom error message provider.
Set minimal valid Date value for schema.
OptionalerrorMessage: ValidationErrorMessageProvider<Custom error message provider.
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<Date> — prevents mutation of
Date methods like setFullYear() at the type level. Validation
behaviour is unchanged.
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).
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.
Allows to create Date schema. It can be required or optional. It can be restricted to be: equal to a certain value, in future, in past, in a certain range. Supports parsing from JSON string and UNIX epoch (using preprocessors).
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 date() function instead.
Example: ```ts const date = new Date(2020, 0, 2); const schema = date().min(new Date(2020, 0, 1)); const result = schema.validate(date); // result.valid === true // result.object === date ```
Example: ```ts const schema = date(); const result = schema.validate('2020-01-01'); // result.valid === false // result.errors[0].message === 'is expected to be a date' ```
Example: ```ts const schema = date().parseFromJson(); const result = schema.validate('2020-01-01T00:00:00.000Z'); // result.valid === true // result.object is equal to corresponding Date object ```
Example: ```ts const schema = date().parseFromEpoch(); const result = schema.validate(1577836800000); // result.valid === true // result.object is equal to corresponding Date object ```
See
date