Schemas

Strings

vld::string() — length, patterns, transforms, coercion and more than 40 built-in formats.

vld::string() returns a ZString whose output is String. Checks are chained and all of them run, so one parse can report several issues.

use vld::prelude::*;

let username = vld::string()
    .trim()
    .to_lowercase()
    .min(3)
    .max(20)
    .alphanumeric();

assert_eq!(username.parse(r#""  Ada42 ""#).unwrap(), "ada42");

Length

Lengths count characters (Unicode scalar values), not bytes.

MethodCheckIssue
min(n)at least n characterstoo_small (origin string)
max(n)at most n characterstoo_big (origin string)
len(n)exactly n charactersinvalid_length
non_empty()at least one charactertoo_small
min_bytes(n) / max_bytes(n)UTF-8 length in bytes (byte-limited storage)too_small / too_big (origin bytes); not in the JSON Schema, which has no byte keyword

JavaScript ("é".length, Zod .max()) counts UTF-16 code units, so a character limit and a JS limit differ for emoji and other characters outside the BMP.

Content

MethodCheck
starts_with("pre")prefix
ends_with("suf")suffix
contains("sub")substring
pattern(r"...")regular expression (feature regex), see below
rule(r)a reusable custom rule

Patterns

With the regex feature, pattern checks a regular expression and emits it as the JSON Schema pattern. It takes the source (panics on an invalid one, like Regex::new(..).unwrap()) or a prebuilt vld::rules::Pattern; the pattern is compiled once, when the schema is built.

// feature = "regex"
let sku = vld::string().pattern(r"^[A-Z]{3}-\d{4}$");
assert!(sku.parse(r#""ABC-1234""#).is_ok());

// Handle an invalid pattern instead of panicking:
let p = vld::rules::Pattern::new(user_input)?;
let s = vld::string().pattern_msg(p, "Wrong SKU");

A failure is invalid_string (StringValidation::Regex, with_messages key invalid_regex). Matching uses regex-lite: linear time (no ReDoS), Rust syntax without look-around or backreferences, no Unicode classes such as \p{L}.

Most checks need no regex: every format below is a hand-written parser. Reach for pattern only for shapes that are not built in, and write a rule when the check is easier in Rust or too much for regex-lite.

Transforms and coercion

Transforms run before the checks, in the order they were added.

MethodEffect
trim()strip leading and trailing whitespace
to_lowercase()lowercase the input
to_uppercase()uppercase the input
coerce()accept numbers and booleans and turn them into text (42 → "42")
truncate(n)keep the first n characters (cut instead of rejecting)
coerce_bools(on, off)coerce(), writing booleans as on / off (coerce_bools("1", "0"): true → "1")
normalize_nfc()Unicode NFC: e + U+0301 → é, so equal-looking text compares and counts equal (feature unicode)
normalize_nfkc()Unicode NFKC: also folds full-width forms and ligatures (fi, fi → fi); the form to compare usernames in (feature unicode)

Formats

Every format method has a _msg twin that takes a custom message (email_msg("...")). A failed format check reports IssueCode::InvalidString { validation }, key invalid_string. Each format also sets the JSON Schema format keyword.

Network

MethodAccepts
email()email address
url()http / https URL
url_strict()public http / https URL: real host, not localhost, private, loopback, link-local or unspecified addresses (IPv4-mapped IPv6 included). Feature string-advanced
uri()any URI (feature string-advanced)
ip()IPv4 or IPv6 address
ipv4() / ipv6()one address family (IPv6 accepts IPv4-mapped forms)
cidr()IPv4 / IPv6 CIDR block with a decimal prefix
mac()MAC address xx:xx:xx:xx:xx:xx
hostname()DNS hostname

Identifiers

MethodAccepts
uuid()any UUID
uuid_v1() / uuid_v4() / uuid_v7()a specific UUID version (feature string-advanced)
cuid2()CUID2: 2–32 lowercase alphanumerics starting with a letter
ulid()26-character Crockford Base32 ULID
nanoid()Nano ID alphabet (alphanumerics, _, -)
slug()URL slug [a-z0-9-]
semver()MAJOR.MINOR.PATCH with an optional v prefix
semver_full()full semantic version parsed by the semver crate (feature string-advanced)
jwt()JWT-shaped token header.payload.signature (base64url parts; the signature is not verified)
credit_card()12–19 digits with optional spaces or dashes, Luhn-checked
phone()international phone: leading +, 8–15 digits, optional spaces, dashes, parentheses
phone_e164_strict()strict E.164, checked with phonenumber (feature string-advanced)
currency_code()an active ISO 4217 code with minor units (USD, JPY; the table money() uses): withdrawn codes (HRK), metals and test codes (XAU, XTS) are rejected
country_code()two uppercase letters (ISO 3166 alpha-2 shape)
country() / country_alpha3()an assigned ISO 3166-1 alpha-2 (US; UK is not) / alpha-3 (USA) code
iban()IBAN: uppercase, optional single spaces between groups, the country's registry length, mod-97 checksum
bic()BIC / SWIFT: 8 or 11 uppercase characters with a real country in positions 5–6
isbn()ISBN-10 (check X allowed) or ISBN-13 (978 / 979) with its check digit; single - / space separators
ean()EAN-8, UPC-A (12), EAN-13, GTIN-14 digits with the GS1 check digit
vin()17-character VIN (no I, O, Q) with the North American check digit (49 CFR 565) in position 9; European VINs often have none — use a pattern for them
object_id()MongoDB ObjectId: 24 hex digits
locale()ll or ll-RR (en, en-US)
timezone()IANA time zone name. With feature jiff: present in jiff's time zone database and spelled as there (Europe/Berlin); without it, the shape only (1–3 /-separated parts starting with an uppercase letter)
cron()cron: 5 fields (min hour dom month dow) or 6 (seconds first) of *, values, ranges a-b, lists and /step, all in range; month / weekday names (JAN, mon), ? in the day fields, weekday 7 = Sunday; or @yearly / @annually / @monthly / @weekly / @daily / @midnight / @hourly. Quartz L / W / # are rejected
mime()media type type/subtype[+suffix] with optional ; name=value parameters (token or quoted value)
color()#RRGGBB, #RRGGBBAA, rgb(...), hsl(...)

Text

MethodAccepts
ascii()ASCII only
alpha()ASCII letters only
alphanumeric()ASCII letters and digits
lowercase() / uppercase()already lower / upper case (use to_lowercase() to convert instead)
emoji()non-empty, emoji only
json()a string that contains exactly one JSON document
regex_syntax()the value itself compiles as a regular expression (feature regex, regex-lite syntax; the JSON Schema format: regex means ECMA-262, which differs in details)
single_script()no mixed scripts (Unicode TS #39; Common / Inherited characters and Han + Kana / Hangul allowed): rejects spoofs such as pаypal with a Cyrillic а (feature unicode)

Passwords

Each rule is its own check and reports its own issue, so a form can list every unmet rule at once. Lengths use min / max.

MethodRuleStringValidation
require_lowercase()a lowercase letter (Unicode Lowercase)PasswordLowercase (password_lowercase)
require_uppercase()an uppercase letter (Unicode Uppercase)PasswordUppercase
require_digit()an ASCII digitPasswordDigit
require_symbol()a character that is neither alphanumeric nor whitespacePasswordSymbol
max_repeat(n)no character more than n times in a rowPasswordRepeat { max_repeat }
password_strength(score)the zxcvbn estimate is at least score (0–4; feature password-strength)PasswordStrength { min_score }
let password = vld::string()
    .min(12)
    .require_lowercase()
    .require_uppercase()
    .require_digit()
    .require_symbol()
    .max_repeat(2)
    .redact(); // the value never appears in errors, see the security guide

Every rule has a _msg twin; with_messages keys are invalid_password_lowercase, …, invalid_password_strength. The JSON Schema gets format: "password" and an x-password object ({"lowercase": true, "maxRepeat": 2, …}), which vld::ts turns into refinements and vld::fake honours. Use redact() on password fields.

Dates and times as strings

These keep the value a String. To get typed dates, use the date schemas.

MethodAccepts
iso_date()YYYY-MM-DD with a real day of month
iso_datetime()YYYY-MM-DDTHH:MM:SS[.frac] (seconds required, T or t), optional Z / z / ±HH:MM; the same grammar as vld::chrono::datetime()
iso_time()HH:MM[:SS[.frac]]

Encodings

MethodAccepts
base64()standard Base64 with padding
base64url()URL-safe alphabet (-, _), padding optional; rejects + and /
hex()hexadecimal characters only

To decode into bytes instead of keeping text, use vld::bytes().base64().

Typed UUID and URL

string().uuid() and string().url() keep a String. With string-advanced, vld::uuid() parses into uuid::Uuid and vld::url() into url::Url (any absolute URL, as uri()); the issues and JSON Schema (format: uuid / uri) are those of the string format. checks(|s| ...) adds string checks before parsing. uuid::Uuid and url::Url implement VldType, so #[derive(Validate)] infers these schemas for such fields.

// feature = "string-advanced"
let id: uuid::Uuid = vld::uuid().parse(r#""550e8400-e29b-41d4-a716-446655440000""#)?;
let v7 = vld::uuid().checks(|s| s.uuid_v7());
let hook = vld::url().checks(|s| s.url_strict()); // public http(s) only

Messages

type_error, <check>_msg (min_msg, email_msg, pattern_msg, …) and with_messages by key: see Custom messages.