Skip to main content

ZObject

Struct ZObject 

Source
pub struct ZObject { /* private fields */ }
Expand description

Dynamic object schema with runtime-defined fields.

For compile-time type-safe objects, use the schema! macro instead.

§Unknown field handling

  • strip() (default) — unknown fields are silently removed from the output.
  • strict() — unknown fields cause a validation error.
  • passthrough() — unknown fields are kept as-is in the output.

§Example

use vld::prelude::*;

let schema = vld::object()
    .field("name", vld::string().min(1))
    .field("age", vld::number().int().min(0));

Implementations§

Source§

impl ZObject

Source

pub fn new() -> Self

Create the schema (the same as its vld:: constructor function).

Source

pub fn field<S: DynSchema + Send + Sync + 'static>( self, name: impl Into<String>, schema: S, ) -> Self

Add a field with its validation schema. A field with the same name is replaced.

With the openapi feature the field keeps its JSON Schema, its required status (.optional() / .nullish() / .with_default(...) / .nullable() are not required) and its named nested schemas.

Source

pub fn field_optional<S: DynSchema + Send + Sync + 'static>( self, name: impl Into<String>, schema: S, ) -> Self

Add a field that is automatically optional (null/missing → null).

The field won’t cause a validation error if it is missing or null. When the value is missing/null the inner schema still runs first, so .with_default(...) and .catch(...) produce their value; otherwise the output is null.

§Example
use vld::prelude::*;

let schema = vld::object()
    .field("name", vld::string().min(1))
    .field_optional("nickname", vld::string().min(1));

let result = schema.parse(r#"{"name": "Alice"}"#).unwrap();
assert_eq!(result.get("nickname").unwrap(), &serde_json::Value::Null);
Source

pub fn strict(self) -> Self

Reject unknown fields not defined in the schema.

Source

pub fn strip(self) -> Self

Silently remove unknown fields from the output (default behavior).

Source

pub fn passthrough(self) -> Self

Keep unknown fields as-is in the output without validation.

Source

pub fn omit(self, name: &str) -> Self

Remove a field definition by name. Returns self for chaining.

Useful with extend() to override fields.

Source

pub fn pick(self, names: &[&str]) -> Self

Keep only the listed fields, removing all others.

Source

pub fn extend(self, other: ZObject) -> Self

Merge another object schema into this one.

If both schemas define the same field, the one from other wins (and takes its place at the end). other’s settings are merged too: its unknown-field mode (when not the default strip()), catchall, min_keys / max_keys win when set, and its when rules are added.

Source

pub fn merge(self, other: ZObject) -> Self

Alias for extend.

Source

pub fn partial(self) -> Self

Make all fields optional: null/missing values return null in the output instead of failing validation.

Equivalent to Zod’s .partial().

Source

pub fn required(self) -> Self

Make all fields required: null values will fail validation. This is the opposite of partial().

Source

pub fn catchall<S: DynSchema + Send + Sync + 'static>(self, schema: S) -> Self

Validate unknown fields using the given schema instead of stripping/rejecting them.

When set, unknown fields are parsed through the catchall schema regardless of the unknown field mode.

Source

pub fn when<S: DynSchema + Send + Sync + 'static>( self, condition_field: impl Into<String>, condition_value: impl Into<Value>, target_field: impl Into<String>, schema: S, ) -> Self

Add a conditional validation rule.

When condition_field has the given value, target_field is validated with the provided schema in addition to any existing field schemas. Under strict() an undeclared target_field is not reported as unrecognized.

§Example
use vld::prelude::*;

let schema = vld::object()
    .field("role", vld::string())
    .field_optional("admin_key", vld::string())
    .when("role", "admin", "admin_key", vld::string().min(10));

// When role != "admin", admin_key is optional and any value is fine
let ok = schema.parse(r#"{"role": "user"}"#);
assert!(ok.is_ok());

// When role == "admin", admin_key must pass the extra schema
let err = schema.parse(r#"{"role": "admin", "admin_key": "short"}"#);
assert!(err.is_err());
Source

pub fn min_keys(self, n: usize) -> Self

Require at least this many keys in the input object.

Source

pub fn max_keys(self, n: usize) -> Self

Require at most this many keys in the input object.

Source

pub fn keyof(&self) -> Vec<String>

Get the list of field names defined in this schema.

Source§

impl ZObject

Source

pub fn to_json_schema(&self) -> Value

Available on crate feature openapi only.

JSON Schema of this object; same as JsonSchema::json_schema.

Trait Implementations§

Source§

impl CollectNestedSchemas for ZObject

Available on crate feature openapi only.
Source§

fn collect_nested_schemas(&self, out: &mut Vec<NestedSchemaEntry>)

Add the named schemas this schema references to _out (for components.schemas).
Source§

impl Default for ZObject

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl JsonSchema for ZObject

Available on crate feature openapi only.

Properties from the fields (with their own schemas and required status); additionalProperties is false for strict(), the catchall schema when set, true otherwise.

Source§

fn json_schema(&self) -> Value

Generate a JSON Schema representation.
Source§

fn is_required(&self) -> bool

Whether this schema should be included in an object’s required array. Read more
Source§

impl VldSchema for ZObject

Source§

type Output = Map<String, Value>

The Rust type produced by this schema after successful parsing.
Source§

fn parse_value(&self, value: &Value) -> Result<Map<String, Value>, VldError>

Parse and validate a serde_json::Value.
Source§

fn parse_missing(&self) -> Result<Self::Output, VldError>

Parse an object field whose key is absent. Read more
Source§

fn parse<I: VldInput + ?Sized>( &self, input: &I, ) -> Result<Self::Output, VldError>

Parse from any supported input (JSON string, file path, serde_json::Value, etc.)
Source§

fn validate<T: Serialize>(&self, value: &T) -> Result<Self::Output, VldError>

Validate an existing Rust value against this schema. Read more
Source§

fn is_valid<T: Serialize>(&self, value: &T) -> bool

Check if an existing Rust value passes this schema’s validation. Read more
Source§

fn optional(self) -> ZOptional<Self>

Make this field optional. Missing or null values become None.
Source§

fn nullable(self) -> ZNullable<Self>

Allow null values. Null becomes None.
Source§

fn with_default(self, value: Self::Output) -> ZDefault<Self>
where Self::Output: Clone,

Provide a default value when the field is missing or null.
Source§

fn blank_as(self, value: Self::Output) -> ZDefault<Self>
where Self::Output: Clone,

Like with_default, and a blank string (empty or whitespace only) also becomes value: legacy stores that write "" or null for “unset”. Read more
Source§

fn refine<F>(self, check: F, message: &str) -> ZRefine<Self, F>
where F: Fn(&Self::Output) -> bool,

Add a custom refinement check without changing the output type.
Source§

fn rule<R>(self, rule: R) -> ZRule<Self, R>
where Self: Sized, R: Rule<Self::Output>,

Check the output with a reusable Rule (output type unchanged). Read more
Source§

fn rule_msg<R>(self, rule: R, msg: impl Into<String>) -> ZRule<Self, R>
where Self: Sized, R: Rule<Self::Output>,

rule with a custom error message.
Source§

fn try_transform<F, U, E>(self, f: F) -> ZTryTransform<Self, F, U>
where F: Fn(Self::Output) -> Result<U, E>, E: Display,

Transform the output with a fallible function; an Err becomes a validation issue (Custom { code: "transform" }, message = the error). Read more
Source§

fn transform<F, U>(self, f: F) -> ZTransform<Self, F, U>
where F: Fn(Self::Output) -> U,

Transform the output value after successful parsing.
Source§

fn nullish(self) -> ZNullish<Self>

Make this field nullish (both optional and nullable).
Source§

fn catch(self, fallback: Self::Output) -> ZCatch<Self>
where Self::Output: Clone,

Return a fallback value on ANY validation error.
Source§

fn pipe<S: VldSchema>(self, next: S) -> ZPipe<Self, S>
where Self::Output: Serialize,

Chain this schema’s output into another schema. Read more
Source§

fn describe(self, description: &str) -> ZDescribe<Self>

Attach a human-readable description/label to this schema. Read more
Source§

fn super_refine<F>(self, check: F) -> ZSuperRefine<Self, F>
where F: Fn(&Self::Output, &mut VldError),

Add a custom refinement that can produce multiple errors. Read more
Source§

fn or<B: VldSchema>(self, other: B) -> ZUnion2<Self, B>

Create a union: this schema or another. Returns Either<Self::Output, B::Output>.
Source§

fn and<B: VldSchema>(self, other: B) -> ZIntersection<Self, B>

Create an intersection: input must satisfy both schemas.
Source§

fn message(self, msg: impl Into<String>) -> ZMessage<Self>

Override the error message for this schema. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> DynSchema for T

Source§

fn dyn_parse(&self, value: &Value) -> Result<Value, VldError>

Parse value and return the output serialized back to JSON.
Source§

fn dyn_parse_missing(&self) -> Result<Value, VldError>

VldSchema::parse_missing of the erased schema.
Source§

fn dyn_json_schema(&self) -> Value

Available on crate feature openapi only.
JSON Schema of the erased schema.
Source§

fn dyn_is_required(&self) -> bool

Available on crate feature openapi only.
Whether this field belongs in an object’s JSON Schema required array.
Source§

fn dyn_collect_nested_schemas( &self, out: &mut Vec<(&'static str, fn() -> Value)>, )

Available on crate feature openapi only.
Collect named nested schemas (OpenAPI components) referenced by this schema.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Schema for T

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.