valid8r - A Comprehensive Validation Framework for Rust
This crate provides a powerful, extensible validation framework for Rust structs. It consists of two crates that work together:
valid8r(this crate): Core validation traits and built-in validatorsvalid8r_derive: Procedural macros for#[derive(Validate)]
It is derived from the validator crate
by Vincent Prouillet and extends it with additional validators (phone numbers,
consent, conditional presence/prohibition), PATCH semantics, and sensitive-value
redaction.
Installation
Requires Rust 1.94 or later. Add this to Cargo.toml:
[]
= { = "0.1", = ["full"] }
The Validate derive macro is included without a feature flag. No optional
features are enabled by default; use full for all optional validators, or
enable only the features you need (see Feature Flags).
Architecture Overview
┌─────────────────────────────────────────────────────────────────────┐
│ HTTP Request │
└───────────────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ Your web layer (e.g. Axum/Actix extractors) │
│ │
│ 1. Deserializes request body/query │
│ 2. Calls T::validate() │
│ 3. Returns validated T or structured errors │
└───────────────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ valid8r_derive crate (Procedural Macro) │
│ #[derive(Validate)] │
│ │
│ Generates impl Validate for T by: │
│ - Parsing #[validate(...)] attributes │
│ - Generating validation code for each field │
│ - Combining results into ValidationErrors │
└───────────────────────────────┬─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────┐
│ valid8r crate (This Crate) │
│ │
│ Provides: │
│ - Validate and ValidateArgs traits │
│ - ValidationError and ValidationErrors types │
│ - Built-in validator traits (ValidateEmail, ValidateLength, etc.) │
└─────────────────────────────────────────────────────────────────────┘
Table of Contents
- Available Validators
- Optional Fields
- PATCH Semantics
- Nested Validation
- Schema Validation
- Custom Error Messages and Codes
- Validation Context
Available Validators
String/Format Validators
email
Validates that a string is a valid email address (HTML5 spec compliant).
# use Validate;
Supported types: String, &str, Cow<str>, Option<T> where T implements ValidateEmail
url
Validates that a string is a valid URL.
#
#
Requires: the url cargo feature (not in the default set)
phone_number
Validates phone numbers using the phonenumber crate.
#
#
Requires: the phone_number cargo feature (not in the default set)
Country codes: Use ISO 3166-1 alpha-2 codes (e.g., "US", "GB", "DE", "FR")
credit_card
Validates credit card numbers using the Luhn algorithm.
#
#
Requires: the cards cargo feature (not in the default set)
ip
Validates IP addresses (v4, v6, or both).
# use Validate;
regex
Validates against a regular expression pattern.
use LazyLock;
use Regex;
# use Validate;
// Define regex as a static for efficiency
static USERNAME_RE: = new;
Note: Always use static/lazy patterns for performance.
non_control_character
Validates that a string contains no control characters.
# use Validate;
Numeric Validators
range
Validates that a number falls within a specified range.
# use Validate;
Supported types: All numeric primitives (u8-u128, i8-i128, f32, f64),
rust_decimal::Decimal, Option<T>, Option<Option<T>>
length
Validates the length of strings, collections, and arrays.
# use Validate;
Supported types: String, &str, Vec<T>, HashMap, HashSet, BTreeMap,
BTreeSet, VecDeque, [T; N], &[T], Cow<str>
Note: For strings, length is measured in Unicode characters, not bytes.
Presence Validators
required
Validates that an Option field contains a value.
# use Validate;
required_if
Conditionally requires a field based on a function.
# use Validate;
required_with
Field is required if ANY of the specified fields have a value.
# use Validate;
required_with_all
Field is required if ALL specified fields have values.
# use Validate;
required_without
Field is required if ANY of the specified fields are missing.
# use Validate;
required_without_all
Field is required if ALL specified fields are missing.
# use Validate;
Conditional Validators (Prohibited)
prohibited_if
Field must be None if a condition is met.
# use Validate;
prohibited_with
Field must be None if ANY of the specified fields have values.
# use Validate;
prohibited_with_all
Field must be None if ALL specified fields have values.
prohibited_without
Field must be None if ANY of the specified fields are missing.
prohibited_without_all
Field must be None if ALL specified fields are missing.
Container Validators
contains
Validates that a string contains a specific substring. Works with String, &str,
Cow<str>, and HashMap<String, V> (checks key presence).
# use Validate;
use HashMap;
does_not_contain
Validates that a string or collection does NOT contain a specific value.
# use Validate;
Comparison Validators
must_match
Validates that two fields have the same value.
# use Validate;
Consent Validators
accepted
Validates that a boolean field is true or a string is an accepted value.
# use Validate;
declined
Validates that a boolean field is false or a string is a declined value.
# use Validate;
accepted_if / declined_if
Conditionally requires acceptance/decline based on a function.
# use Validate;
Custom Validators
custom
Use a custom function for validation. Multiple custom validators can be applied.
use ;
Optional Fields
All validators automatically handle Option<T> fields. When a field is None,
validation is skipped (unless using required validators).
# use Validate;
let profile = Profile ;
assert!;
PATCH Semantics
For PATCH (partial update) operations, you need to distinguish between three states:
- Absent - Field not sent in the request (don't update)
- Null - Field explicitly set to
null(clear/reset the field) - Value - Field has a value (update to the new value)
The validation framework supports two approaches: Option<Option<T>> and Delta<T>.
Using Option<Option<T>>
The traditional approach uses nested Options with a custom deserializer:
# use Validate;
// Example: Clear area_id without providing country_id - VALID
let update = UpdateUser ;
assert!;
// Example: Set area_id but missing country_id - INVALID
let update = UpdateUser ;
assert!;
Using Delta<T> (Recommended)
Delta<T> (from the delta crate) is a three-state enum that models a PATCH
field directly, with less boilerplate than Option<Option<T>>:
Delta::Unchanged— field omitted from the request (leave the stored value)Delta::Clear— field explicitly set tonull(clear the stored value)Delta::Set(value)— field sent with a value (set the stored value)
use Delta;
use Deserialize;
use Validate;
Delta<T> Helper Methods
use Delta;
let unchanged: = Unchanged;
let clear: = Clear;
let set: = Set;
// Check the state
assert!; // field was omitted
assert!; // field was explicitly set to null
assert!; // field has a value
// Access the inner value
assert_eq!;
let inner: = set.into_value;
Comparison: Option<Option<T>> vs Delta<T>
| Aspect | Option<Option<T>> |
Delta<T> |
|---|---|---|
| Serde annotation | #[serde(default, deserialize_with = "...")] |
#[serde(default)] |
| Validation support | ✅ Full | ✅ Full |
| Cross-field validators | ✅ Works | ✅ Works |
| Pattern matching | Nested Some(Some(_)) |
Delta::Set(_) |
| Helper methods | None | is_unchanged(), is_clear(), is_set(), value() |
Semantics Summary (applies to both types):
| State | Option<Option<T>> |
Delta<T> |
Validators Run |
|---|---|---|---|
| Absent | None |
Delta::Unchanged |
Skipped |
| Null | Some(None) |
Delta::Clear |
Skipped |
| Value | Some(Some(v)) |
Delta::Set(v) |
Validated |
Validators that work with Delta<T>
All validators work with Delta<T>:
- Format validators:
email,url,phone_number,credit_card,ip,regex - Presence validators:
required,required_if,required_with,required_without - Prohibition validators:
prohibited_if,prohibited_with,prohibited_without - Numeric validators:
range - String validators:
length,contains,does_not_contain - Custom validators:
custom
Nested Validation
Validate nested structs using the nested attribute:
# use Validate;
Use nest_all_fields to automatically validate all nested structs:
# use Validate;
#
#
Schema Validation
For complex cross-field validation, use schema validation:
use ;
Multiple schema validators:
# use ;
#
#
Note: Schema validation only runs if all field validations pass (to avoid
operating on invalid data). Use skip_on_field_errors = false to override:
# use ;
#
Custom Error Messages and Codes
All validators support custom error messages and codes:
# use Validate;
Validation Context
Pass additional context to validators using ValidateArgs:
use ;
// Usage:
let ctx = ValidationContext ;
let order = Order ;
order.validate_with_args;
Skipping Fields
Skip validation for specific fields:
# use Validate;
Feature Flags
No features are enabled by default.
email: Enable validation of the host part of an email (viaidna)url: Enable URL validationphone_number: Enable phone number validationcards: Enable credit card validationindexmap: Enable validation forIndexMapandIndexSetfull: Enable all of the above
Error Handling
Validation errors are collected in [ValidationErrors]:
# use Validate;
#
#
let user = User ;
match user.validate
Integration with web frameworks
Validation composes naturally with extractors: deserialize the payload,
call validate(), and reject the request with the structured errors on
failure. A typical Axum extractor looks like:
use ;
use Deserialize;
use Validate;
// A custom extractor that deserializes JSON and then calls `validate()`,
// turning `ValidationErrors` into a 422 response.
async
let app = new.route;
License
Licensed under either MIT or Apache License, Version 2.0, at your option. The MIT license includes the original upstream copyright notice.