Schemas

Modifiers

optional, nullable, nullish, with_default and catch.

Modifiers are methods of the VldSchema trait, so they work on every schema.

Methodabsent keynullinvalid valueOutputJSON SchemaTypeScript (vld::ts)
.optional()NoneNoneerrorOption<T>inner schema, not requiredx?: T
.nullable()missing_fieldNoneerrorOption<T>anyOf: [inner, null], requiredx: T | null
.nullish()NoneNoneerrorOption<T>anyOf: [inner, null], not requiredx?: T | null
.with_default(v)vverrorTinner + default, not requiredx?: T
.catch(v)vvvTinner, not requiredx?: T
use vld::prelude::*;

let age = vld::u8().optional();
assert_eq!(age.parse("null").unwrap(), None);
assert_eq!(age.parse("30").unwrap(), Some(30));
assert!(age.parse("-1").is_err());

let page = vld::u32().min(1).with_default(1);
assert_eq!(page.parse("null").unwrap(), 1);
assert!(page.parse("0").is_err()); // present but invalid: still an error

let theme = vld::enumeration(&["light", "dark"]).catch("light".to_string());
assert_eq!(theme.parse(r#""purple""#).unwrap(), "light");

optional, nullable, nullish

optional() also accepts null, although its schema has no null type: serde writes a None field as null, so validate() of a struct with None must pass. Use nullish() when clients may send null and the schema should say so. partial() makes fields optional. Wrappers (describe, refine, transform, rule, catch, …) keep these semantics.

with_default

The default is used only for null or a missing key. A value that is present and invalid still fails. With openapi, the default is emitted as "default": value (the output type must implement serde::Serialize).

blank_as(v) is with_default(v) that also takes a blank string ("" or whitespace only): vld::number().int().coerce().blank_as(0) reads "", null and a missing key as 0. Its JSON Schema is anyOf: [<inner>, {"type": "string", "pattern": "^\\s*$"}] with the default.

impl_default! builds Default from the field types, not from schema defaults; to get schema defaults, parse an empty object. See schema! macro.

catch

catch(v) returns v on any error, including wrong types. Use it for tolerant reading of optional settings; avoid it for input you need to reject.