Skip to main content

Crate vld

Crate vld 

Source
Expand description

§vld — type-safe runtime validation for Rust

vld is a validation library inspired by Zod. Schemas are values: chain checks on them, then parse untrusted input (JSON text, bytes, files or serde_json::Value) into typed Rust values. A failed parse returns a VldError with every issue, each with a path, a typed IssueCode and a message.

Guide: https://s00d.github.io/vld/ · Changelog / migration from 0.4: https://s00d.github.io/vld/guides/migration

§Quick start

use vld::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String => vld::string().trim().min(2).max(50),
        pub email: String => vld::string().email(),
        pub age: Option<i64> => vld::number().int().gte(18).optional(),
    }
}

let user = User::parse(r#"{"name": " Alex ", "email": "alex@example.com"}"#).unwrap();
assert_eq!(user.name, "Alex");
assert_eq!(user.age, None);

let err = User::parse(r#"{"name": "A", "email": "nope"}"#).unwrap_err();
assert_eq!(err.issues.len(), 2);
assert_eq!(err.issues[0].code.key(), "too_small");

Single values work the same way:

use vld::prelude::*;

let port = vld::u16().min(1024);
assert_eq!(port.parse("8080").unwrap(), 8080);
assert!(port.parse("80").is_err());

§Features

None are enabled by default.

FeatureEnables
derive#[derive(Validate)]
openapithe JsonSchema trait and OpenAPI 3.1 documents
diffbreaking-change detection between JSON Schemas (implies openapi)
regexstring().pattern(...), rules::Pattern (via regex-lite)
chrono / jiff / timevld::chrono, vld::jiff, vld::time date schemas (additive)
decimaldecimal() (rust_decimal)
netip_network() (ipnet)
file / file-advancedfile() with size / type checks; hashes, image size, EXIF
string-advancedurl_strict(), uri(), uuid_v4() & co, phone_e164_strict(), semver_full()

§Module map

§Size method names

Size bounds are named after what they count:

SchemaBoundsExact
string() (characters)min / maxlen
array(), bytes() (items / bytes)min_len / max_lenlen
set() (unique items), file() (bytes)min_size / max_size—
object(), record() (keys)min_keys / max_keys—
numbers, datesmin / max (gt / lt exclusive)—

schema! structs get parse(); #[derive(Validate)] generates vld_parse() instead, as parse would clash with clap::Parser::parse and similar derives.

Re-exports§

pub use error::format;
pub use error::i18n;
pub use openapi as json_schema;openapi
pub use openapi::diff;diff
pub use schema::Schema;
pub use schema::input;
pub use primitives::date::chrono;chrono
pub use primitives::date::jiff;jiff
pub use primitives::date::time;time

Modules§

collections
Arrays, tuples, sets, maps and records.
combinators
Unions, intersections, refinements, transforms and pipes.
de
Bridge to serde: validate a field while serde deserializes the struct, so one decoder does both.
error
Validation errors: VldError, ValidationIssue, IssueCode.
modifiers
Optional, nullable, nullish and default wrappers.
object
Dynamic objects (ZObject) and lenient-parsing results.
openapiopenapi
JSON Schema / OpenAPI generation from vld schemas.
prelude
Common imports for working with vld.
primitives
Strings, numbers, booleans, dates and other leaf schemas.
rules
Reusable validation rules.
schema
The VldSchema / VldParse traits and nested-schema helpers.

Macros§

deserialize_fn
A serde deserialize_with function that parses with a vld schema (built once per process).
impl_default
Generate impl Default for a struct created by schema!.
impl_rules
Attach validation rules to an existing struct.
impl_validate_fields
Generate validate_fields() and parse_lenient() methods for a struct previously defined with schema!.
nested
Create a named nested schema with $ref generation and full JSON Schema.
schema
Define a validated struct with field-level schemas.
schema_validated
Combined macro: generates the struct, parse(), and validate_fields() / parse_lenient() in a single declaration — no need to repeat field schemas.
union
Create a union schema from 2 or more schemas.

Functions§

any
Create a schema that accepts any JSON value.
array
Create an array validation schema.
boolean
Create a boolean validation schema.
bytes
Create a bytes validation schema (Vec<u8>).
char
Create a single-char schema (a string of exactly one Unicode scalar value).
custom
Create a schema from a custom validation function.
decimaldecimal
Create a decimal validation schema (rust_decimal::Decimal).
discriminated_union
Create a discriminated union schema.
duration
Create a duration validation schema (std::time::Duration).
enum_of
Map fixed strings to values of T — a light alternative to from_serde() for enums without Deserialize.
enumeration
Create a string enum schema. Validates against a fixed set of values.
f32
Create an f32 number schema (rejects values outside the f32 range).
filefile
Create a file validation schema.
from_serde
Deserialize the JSON value into T with serde (Rust enums, uuid::Uuid, url::Url, semver::Version, …).
from_str
Parse a JSON string with T: FromStr (IpAddr, Uuid, Url, numbers as strings, …).
i8
Create a i8 integer schema (exact, range-checked; see primitives::ZInteger).
i16
Create a i16 integer schema (exact, range-checked; see primitives::ZInteger).
i32
Create a i32 integer schema (exact, range-checked; see primitives::ZInteger).
i64
Create a i64 integer schema (exact, range-checked; see primitives::ZInteger).
intersection
Create an intersection of two schemas (input must satisfy both).
ip_networknet
Create an IP network/CIDR schema (ipnet::IpNet).
isize
Create a isize integer schema (exact, range-checked; see primitives::ZInteger).
json_value
Create a raw JSON value schema with shape constraints.
lazy
Create a lazy schema for recursive data structures.
literal
Create a literal value schema. Validates exact match.
map
Create a Map schema. Validates [[key, value], ...] arrays into HashMap.
nested
Create a schema for nested/composed structs.
nested_named
Create a named nested schema. Usually called through nested!.
never
Create a schema that rejects every value (output std::convert::Infallible).
null
Create a schema that accepts only null (output ()).
number
Create a number validation schema (f64).
object
Create a dynamic object validation schema.
path
Create a path validation schema (std::path::PathBuf).
preprocess
Preprocess the JSON value before passing it to a schema.
record
Create a record (dictionary) schema. All values validated by the given schema.
record_with_keys
Create a record whose keys are validated and converted by key_schema.
set
Create a Set schema. Validates arrays into HashSet (unique elements).
socket_addr
Create a socket address schema (std::net::SocketAddr).
string
Create a string validation schema.
u8
Create a u8 integer schema (exact, range-checked; see primitives::ZInteger).
u16
Create a u16 integer schema (exact, range-checked; see primitives::ZInteger).
u32
Create a u32 integer schema (exact, range-checked; see primitives::ZInteger).
u64
Create a u64 integer schema (exact, range-checked; see primitives::ZInteger).
union
Create a union of two schemas. Returns Either<A, B>.
union3
Create a union of three schemas. Returns Either3<A, B, C>.
usize
Create a usize integer schema (exact, range-checked; see primitives::ZInteger).

Derive Macros§

Validatederive
Derive macro that generates vld_parse(), parse_value(), validate() / is_valid(), JSON Schema methods (with openapi) and implements the VldParse trait.