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.
Readonly[Marks this builder as having sub-properties for descriptor tree recursion.
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 object schema over the object.
Throws if any preprocessor, validator, or error message provider returns a Promise.
The returned result includes a getErrorsFor() method for type-safe,
per-property error inspection.
The object to validate against this schema.
Optionalcontext: ValidationContext<Optional ValidationContext settings.
Protected_Performs async validation of object schema over the object.
Supports async preprocessors, validators, and error message providers.
The object to validate against this schema.
Optionalcontext: ValidationContext<Optional ValidationContext settings.
Fields not defined in properties will not be validated
and will be passed through the validation.
Adds a preprocessor to a preprocessors list
Optionaloptions: { mutates?: boolean }Adds a new property to the object schema. The new property will be validated according to the provided schema.
Adds new properties to the object schema. The same as .addProp() but
allows to add multiple properties with one call. The new properties
will be validated according to the provided schemas.
a key/schema object map.
Adds all properties from the schema object schema to the current schema.
an instance of ObjectSchemaBuilder
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.
the fallback value, or a factory function producing the fallback
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.
Remove all validators for this schema.
ProtectedcreateProtected method used to create a new instance of the Builder
defined by the props object. Should be used to instantiate new
builders to keep builder's immutability.
Recursively marks all properties — and all properties of nested
object() schemas — as optional. Useful for PATCH API bodies
and partial form state where every field at every level is optional.
Only nested ObjectSchemaBuilder schemas are recursed into.
Other schema types (arrays, unions, primitives, lazy) are made
optional at the top level but their internals are not modified.
const Address = object({
street: string(),
city: string()
});
const User = object({
name: string(),
address: Address
});
const PatchUser = User.deepPartial();
// PatchUser infers as:
// { name?: string; address?: { street?: string; city?: string } }
PatchUser.validate({ address: { city: 'Paris' } }); // valid
PatchUser.validate({}); // valid
// Three-level nesting
const schema = object({
a: object({
b: object({ c: string() })
})
}).deepPartial();
schema.validate({}); // valid
schema.validate({ a: {} }); // valid
schema.validate({ a: { b: {} } }); // valid
// PATCH API body
const CreateBody = object({
profile: object({ displayName: string(), bio: string() }),
settings: object({ theme: string(), language: string() })
});
const PatchBody = CreateBody.deepPartial();
// All fields are optional at every level —
// send only what you want to update.
partial for shallow-only property optionality.
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: TAdds all properties from schema to the current schema.
TSchema & TAnotherSchema is a good example of the similar concept
in the TS type system.
an object schema to take properties from
Generates a serializable object describing the defined schema
If set to true, schema validation will not
return errors if object contains fields which
are not defined in the schema properties.
Set to false by default
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.
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
Properties defined in schema
Custom error message provider for the 'is required' validation error.
String id of schema type, e.g. string', numberorobject`.
Array of validator functions
Partial<T> would be a good example of the
same operation in the TS world.
Required<T> would be a good example of the
same operation in the TS world.
An alias for .partial(prop: string)
name of the property
Marks prop as required property.
If prop does not exists in the current schema,
an error will be thrown.
name of the property
Modify schema for propName and return a new schema.
Could be useful if you want to leave all schema intact, but
change a type of one property.
name of the property (string)
callback function returning a new schema fo the propName. As a first parameter
you will receive an old schema for propName.
Fields not defined in properties will be considered
as schema violation. This is the default behavior.
Removes the nullable mark — null is no longer accepted as a valid
value. This is the counterpart of .nullable().
Makes schema nullable — null is accepted as a valid value.
Unlike .optional() which accepts undefined, .nullable() accepts
null. The inferred type changes from T to T | null. Combine with
.optional() to accept both null and undefined.
Omits properties listed in properties from the schema.
Consider Omit<Type, 'prop1'|'prop2'...> as a good illustration
from the TS world.
array of property names (strings) to remove from the schema.
Removes propName from the list of properties.
property name to remove. Schema should contain this property. An error will be thrown otherwise.
Removes all properties of schema from the current schema.
Omit<TSchema, keyof TAnotherSchema> as a good illustration
from the TS world.
schema builder to take properties from.
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
Marks all properties in the current schema as optional.
It is the same as call .optional('propname') where propname is the name
of every property in the schema.
Marks all properties from properties as optional in the schema.
list of property names (string) to make optional
Marks property propName as optional in the schema.
the name of the property (string).
Returns a new schema containing only properties listed in
properties array.
array of property names (strings)
Returns new schema based on the current schema. This new schema
will consists only from properties which names are taken from the
schema object schema.
schema to take property names list from
Returns a new schema consisting of only one property
(taken from the property property name). If the property
does not exists in the current schema, an error will be thrown.
the name of the property (string).
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<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<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<T> — all top-level properties
become readonly 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, {}>>Performs synchronous validation of object schema over the object.
Throws if any preprocessor, validator, or error message provider returns a Promise.
The returned result includes a getErrorsFor() method for type-safe,
per-property error inspection.
The object to validate against this schema.
Optionalcontext: ValidationContext<Optional 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).
The object to validate against this schema.
Optionalcontext: ValidationContext<Optional 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.
StaticgetStaticis
Object schema builder class. Similar to the
objecttype in JS. Allows to define a schema forobjectvalue. Should be used to validate objects with specific properties. Properties should be defined as their own schema builders. You can use anySchemaBuildere.g.string(),number(),boolean(),array(),object(), etc. to define properties. Which means that you can define nested objects and arrays of any complexity.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 object() function instead.
Example
Example
Example
Example
See
object