Schemas

Other types

from_serde, from_str, bytes, decimal, IP networks, socket addresses, paths, files, durations and raw JSON.

from_serde and from_str

Bridge any existing Rust type into a schema.

ConstructorReadsError
vld::from_serde::<T>()the JSON value through T: Deserialize (Rust enums, uuid::Uuid, url::Url, …)parse_error with serde's message
vld::from_str::<T>()a JSON string through T: FromStr (IpAddr, numbers in strings, …)invalid_format (from_str) with the error's Display
use vld::prelude::*;
use std::net::IpAddr;

#[derive(Debug, PartialEq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
enum Status { Active, OnHold }

let status = vld::from_serde::<Status>()
    .schema(serde_json::json!({"type": "string", "enum": ["active", "on_hold"]}));
assert_eq!(status.parse(r#""on_hold""#).unwrap(), Status::OnHold);

let ip = vld::from_str::<IpAddr>().parse(r#""::1""#).unwrap();
assert!(ip.is_loopback());

The JSON Schema is {} for from_serde and {"type": "string"} for from_str; set your own with .schema(json).

Bytes

vld::bytes() returns Vec<u8>. By default it reads a JSON array of integers 0..=255.

MethodEffect
base64()also accept a padded Base64 string
base64url()also accept a Base64URL string (+ and / rejected)
hex()also accept a hex string (optional 0x prefix)
min_len / max_len / len / non_empty()size of the decoded bytes
let key = vld::bytes().base64().len(4);
assert_eq!(key.parse(r#""AAECAw==""#).unwrap(), vec![0, 1, 2, 3]);

Decimal

Feature decimal. vld::decimal() returns rust_decimal::Decimal from a JSON string or number (plain or scientific notation). Bounds take strings so they keep full precision:

// features = ["decimal"]
let amount = vld::decimal().non_negative().max("1000000").multiple_of("0.01");
assert!(amount.parse(r#""19.99""#).is_ok());

Methods: min, max, gt, lt, multiple_of, positive, negative, non_negative, non_positive, and the digit checks below.

Scale and precision

MethodCheckIssue
max_scale(n)at most n digits after the pointtoo_big (origin scale, maximum n)
scale(n)exactly n digits after the pointinvalid_length (origin scale, expected n)
max_precision(p)at most p significant digits (p >= 1)too_big (origin precision, maximum p)

The scale is counted as written: "1.230" has scale 3 (trailing zeros count, as money amounts usually want), "1e-7" scale 7, "1.5e2" scale 0. A JSON number arrives in its shortest form, so 1.10 has scale 1 and scale(n) is meant for decimal strings. Precision is the digits of the unscaled value, at least the scale: "123.45" → 5, "0.012" → 3, "1.230" → 4. The checks run after the bounds, in the table's order.

// features = ["decimal"]
let price = vld::decimal().non_negative().max_scale(2).max_precision(10);
assert!(price.parse(r#""19.90""#).is_ok());
assert!(price.parse(r#""19.999""#).is_err()); // too_big, origin scale

with_messages keys: invalid_format, too_small / too_big (bounds and sign checks), not_multiple_of, max_scale, scale, max_precision.

JSON Schema: {"type": ["string", "number"], "format": "decimal"} plus vld's extension keys x-minDecimal / x-maxDecimal (and the exclusive forms), x-multipleOfDecimal, x-maxScale, x-scale, x-maxPrecision. Standard validators ignore the x- keys (a number-only multipleOf cannot describe a decimal string, nor an exact scale); vld::fake honours them.

Money

Feature decimal. vld::money() parses {"amount": <decimal>, "currency": "<ISO 4217 code>"} into vld::primitives::Money { amount: Decimal, currency: String } (Serialize / Deserialize; the amount serializes as a string, keeping its scale).

  • currency must be an active ISO 4217 code with minor units, upper case (USD, JPY, BHD); otherwise invalid_string (currency) at .currency. Precious metals, test and SDR codes (XAU, XTS, XDR) have no minor units and are refused.
  • amount is checked by the amount schema (vld::decimal() unless set with .amount(...)), then its written scale against the currency's minor units: USD 2, JPY 0, BHD 3, CLF 4. "10.50" USD is fine, "10.500" USD and "1.5" JPY are too_big (origin scale) at .amount.
  • .currencies(&["EUR", "USD"]) allows only those codes (invalid_enum_value).
// features = ["decimal"]
let price = vld::money().amount(vld::decimal().positive());
let m = price.parse(r#"{"amount": "12.50", "currency": "EUR"}"#).unwrap();
assert_eq!(m.amount.to_string(), "12.50");
let err = price.parse(r#"{"amount": "100.5", "currency": "JPY"}"#).unwrap_err();
assert_eq!(err.issues[0].path_string(), ".amount");

with_messages keys: currency, plus the amount's (the currency scale rule uses max_scale). JSON Schema: an object with amount (the decimal schema) and currency (format: currency-code, or an enum with currencies), both required, and "x-money": true — the per-currency scale is not expressible in JSON Schema. Money and Decimal implement VldType, so derived fields of those types need no #[vld(...)].

Network types

ConstructorOutputMethods
vld::ip_network() (feature net)ipnet::IpNet from a CIDR stringipv4_only(), ipv6_only()
vld::socket_addr()std::net::SocketAddr from ipv4:port or [ipv6]:port (no hostnames)min_port(p), max_port(p)

For IP addresses as plain strings use string().ip(); for IpAddr use from_str::<IpAddr>().

Duration

vld::duration() returns std::time::Duration. It accepts a non-negative number of seconds (3, 1.5) or a string: "10s", "1.5s", "250ms" (integer milliseconds), or an ISO 8601 duration.

ISO 8601 durations follow the RFC 3339 grammar: weeks alone (P2W), or days and a time part after T with hours, minutes and seconds, each optional but in that order (P3DT4H30M, PT1H, PT15S, P1D). Only the last number may have a fraction (PT1.5H, P0,5D; . or ,, up to 9 digits). A day counts as 86 400 seconds. Years and months (P1Y, P2M, P1Y2M3D) have no fixed length — a month is 28 to 31 days, a year 365 or 366 — so they fail with invalid_format (duration_calendar_unit); do calendar arithmetic with a date library. Other malformed strings are invalid_type.

use std::time::Duration;

let timeout = vld::duration().max_secs(60);
assert_eq!(timeout.parse(r#""250ms""#).unwrap(), Duration::from_millis(250));
assert_eq!(timeout.parse("1.5").unwrap(), Duration::from_millis(1500));
assert_eq!(vld::duration().parse(r#""P1DT2H""#).unwrap(), Duration::from_secs(93_600));
assert!(vld::duration().parse(r#""P1M""#).is_err()); // invalid_format: calendar unit

Bounds: min(Duration), max(Duration), min_secs(u64), max_secs(u64).

Geo

Feature geo (no dependencies).

ConstructorOutputAccepts
vld::latitude() / vld::longitude()f64degrees in -90..=90 / -180..=180 (number presets)
vld::geo_point()vld::primitives::GeoPoint { lat, lng }{"lat": .., "lng": ..} ("lon" also accepted), or [lng, lat]
vld::geojson()serde_json::Value (the input)an RFC 7946 GeoJSON object

A pair is in GeoJSON order: longitude first, [13.405, 52.52] for Berlin — the usual [lat, lng] mistake shows up as a latitude out of range at [1] (or silently swapped when both fit, so prefer the object form in APIs). A pair has exactly two items (no altitude; invalid_length, origin tuple).

// features = ["geo"]
let p = vld::geo_point().parse(r#"{"lat": 52.52, "lng": 13.405}"#).unwrap();
assert_eq!(p, vld::geo_point().parse("[13.405, 52.52]").unwrap());

geojson() accepts the seven geometry types by default; .types(&["Feature", "FeatureCollection"]) (or any subset of the nine) sets the accepted top-level types. Every issue is reported at its exact path:

RuleIssue
object with a known typeinvalid_type / missing_field / invalid_enum_value at .type
position: array of ≥ 2 numbers (altitude allowed)invalid_type, too_small (origin array)
LineString: ≥ 2 positions (also inside MultiLineString)too_small
Polygon ring: ≥ 4 positions, last equal to first (also inside MultiPolygon)too_small, ring_not_closed at the ring
GeometryCollection.geometries, FeatureCollection.featuresper item, e.g. .features[1].geometry.coordinates
Feature: geometry (geometry or null) and properties (object or null), both requiredmissing_field, invalid_type
bbox (optional): 4 or 6 numberstoo_small / too_big / invalid_length

Not checked, as RFC 7946 asks parsers to accept them: ring winding order, coordinate ranges, foreign members (id, title, …). An empty coordinates array passes where the type allows zero items (MultiPoint, Polygon, …), not for Point / LineString.

// features = ["geo"]
let err = vld::geojson()
    .parse(r#"{"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1]]]}"#)
    .unwrap_err();
assert_eq!(err.issues[0].path_string(), ".coordinates[0]");
assert_eq!(err.issues[0].code.key(), "ring_not_closed");

JSON Schema: geo_point() is an anyOf of the object (lat / lng required) and the [lng, lat] tuple; geojson() an anyOf with one object per accepted type, discriminated by "type": {"const": ..} (Zod / Valibot get a discriminated union). Rings carry "x-closedRing": true (closure is not expressible); bbox and nested geometry collections are not described.

Raw JSON

vld::json_value() returns a serde_json::Value with shape constraints: object(), array(), require_key("id"), max_depth(n) (json_too_deep when nesting is deeper). Use vld::any() to accept anything without checks.

Path

vld::path() returns std::path::PathBuf.

MethodCheck
absolute() / relative()path form
exists() / file() / dir()checked against the server's filesystem
within(base)the path must stay inside base; returns base.join(input)

Paths from requests are untrusted: confine them with within(base), which resolves ., .. and existing symlinks before the check (see the security guide).

let upload = vld::path().relative().within("/srv/uploads");
let p = upload.parse(r#""avatars/ada.png""#).unwrap();
assert_eq!(p, std::path::PathBuf::from("/srv/uploads/avatars/ada.png"));
assert!(upload.parse(r#""../etc/passwd""#).is_err()); // path_outside_base

File

Feature file (and file-advanced for hashes, image size and EXIF). vld::file() reads a file path (a string, or an object with a string path) and returns a ValidatedFile with path(), size(), media_type(), extension(), bytes(), read_bytes() and open().

MethodCheck
min_size(bytes) / max_size(bytes) / non_empty()file size; reads stop after max_size + 1 bytes
extension("png") / extensions(&[...]) / deny_extension(..)file extension
media_type("image/*") / media_types(&[...]) / deny_media_type(..)MIME type sniffed from the content (infer; wildcards like image/* allowed)
allow_magic_type("png") / deny_magic_type(..)file kind sniffed from the content, by extension name
sha256(hex) / md5(hex)checksum (file-advanced)
min_width / max_width / min_height / max_heightimage dimensions (file-advanced)
require_exif()image has EXIF data (file-advanced)
within(base)confine the path, as for vld::path()
store_in_memory() (default) / store_path_only()keep the bytes in the output or only the path

vld::file() opens and reads the file named by the input: always add within(base) when the path comes from a client.