Modifiers
Modifiers are methods of the VldSchema trait, so they work on every schema.
| Method | absent key | null | invalid value | Output | JSON Schema | TypeScript (vld::ts) |
|---|---|---|---|---|---|---|
.optional() | None | None | error | Option<T> | inner schema, not required | x?: T |
.nullable() | missing_field | None | error | Option<T> | anyOf: [inner, null], required | x: T | null |
.nullish() | None | None | error | Option<T> | anyOf: [inner, null], not required | x?: T | null |
.with_default(v) | v | v | error | T | inner + default, not required | x?: T |
.catch(v) | v | v | v | T | inner, not required | x?: 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.