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.
| Feature | Enables |
|---|---|
derive | #[derive(Validate)] |
openapi | the JsonSchema trait and OpenAPI 3.1 documents |
diff | breaking-change detection between JSON Schemas (implies openapi) |
regex | string().pattern(...), rules::Pattern (via regex-lite) |
chrono / jiff / time | vld::chrono, vld::jiff, vld::time date schemas (additive) |
decimal | decimal() (rust_decimal) |
net | ip_network() (ipnet) |
file / file-advanced | file() with size / type checks; hashes, image size, EXIF |
string-advanced | url_strict(), uri(), uuid_v4() & co, phone_e164_strict(), semver_full() |
§Module map
schema— theVldSchematrait,VldParse,DynSchema, input sources, nested schemas andparse_coercederror—VldError,IssueCode, formatting (error::format) and translations (error::i18n)primitives,collections,combinators,modifiers,object— schema typesopenapi(featureopenapi) — JSON Schema / OpenAPI generation and schema diffsprelude— everything needed for day-to-day use
§Size method names
Size bounds are named after what they count:
| Schema | Bounds | Exact |
|---|---|---|
string() (characters) | min / max | len |
array(), bytes() (items / bytes) | min_len / max_len | len |
set() (unique items), file() (bytes) | min_size / max_size | — |
object(), record() (keys) | min_keys / max_keys | — |
| numbers, dates | min / 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;openapipub use openapi::diff;diffpub use schema::Schema;pub use schema::input;pub use primitives::date::chrono;chronopub use primitives::date::jiff;jiffpub 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. - openapi
openapi - JSON Schema / OpenAPI generation from
vldschemas. - prelude
- Common imports for working with
vld. - primitives
- Strings, numbers, booleans, dates and other leaf schemas.
- rules
- Reusable validation rules.
- schema
- The
VldSchema/VldParsetraits and nested-schema helpers.
Macros§
- deserialize_
fn - A serde
deserialize_withfunction that parses with a vld schema (built once per process). - impl_
default - Generate
impl Defaultfor a struct created byschema!. - impl_
rules - Attach validation rules to an existing struct.
- impl_
validate_ fields - Generate
validate_fields()andparse_lenient()methods for a struct previously defined withschema!. - nested
- Create a named nested schema with
$refgeneration and full JSON Schema. - schema
- Define a validated struct with field-level schemas.
- schema_
validated - Combined macro: generates the struct,
parse(), andvalidate_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-
charschema (a string of exactly one Unicode scalar value). - custom
- Create a schema from a custom validation function.
- decimal
decimal - 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 tofrom_serde()for enums withoutDeserialize. - enumeration
- Create a string enum schema. Validates against a fixed set of values.
- f32
- Create an
f32number schema (rejects values outside thef32range). - file
file - Create a file validation schema.
- from_
serde - Deserialize the JSON value into
Twith 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
i8integer schema (exact, range-checked; seeprimitives::ZInteger). - i16
- Create a
i16integer schema (exact, range-checked; seeprimitives::ZInteger). - i32
- Create a
i32integer schema (exact, range-checked; seeprimitives::ZInteger). - i64
- Create a
i64integer schema (exact, range-checked; seeprimitives::ZInteger). - intersection
- Create an intersection of two schemas (input must satisfy both).
- ip_
network net - Create an IP network/CIDR schema (
ipnet::IpNet). - isize
- Create a
isizeinteger schema (exact, range-checked; seeprimitives::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 intoHashMap. - 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
u8integer schema (exact, range-checked; seeprimitives::ZInteger). - u16
- Create a
u16integer schema (exact, range-checked; seeprimitives::ZInteger). - u32
- Create a
u32integer schema (exact, range-checked; seeprimitives::ZInteger). - u64
- Create a
u64integer schema (exact, range-checked; seeprimitives::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
usizeinteger schema (exact, range-checked; seeprimitives::ZInteger).
Derive Macros§
- Validate
derive - Derive macro that generates
vld_parse(),parse_value(),validate()/is_valid(), JSON Schema methods (withopenapi) and implements theVldParsetrait.