valid8r_derive - Procedural Macros for Validation
This crate provides the #[derive(Validate)] procedural macro that generates
validation implementations for Rust structs. It is part of the validation
framework and works in conjunction with the valid8r crate.
Installation
Requires Rust 1.94 or later. Use the macro through valid8r, which re-exports it:
[]
= { = "0.1", = ["full"] }
Overview
The derive macro parses #[validate(...)] attributes on struct fields and
generates the impl Validate for T block that performs runtime validation.
┌─────────────────────────────────────────────────────────────────┐
│ Your Struct Definition │
│ #[derive(Validate)] │
│ struct User { │
│ #[validate(email)] │
│ email: String, │
│ } │
└─────────────────────────────────────────────────────────────────┘
│
▼ (compile time)
┌─────────────────────────────────────────────────────────────────┐
│ valid8r_derive (This Crate) │
│ │
│ 1. Parse #[validate(...)] attributes using darling │
│ 2. Generate validation code for each field │
│ 3. Output impl Validate for User { ... } │
└─────────────────────────────────────────────────────────────────┘
│
▼ (runtime)
┌─────────────────────────────────────────────────────────────────┐
│ user.validate() → Runs generated validation code │
│ → Returns Ok(()) or Err(ValidationErrors) │
└─────────────────────────────────────────────────────────────────┘
Basic Usage
use Validate;
let user = CreateUser ;
assert!;
Struct-Level Attributes
These attributes are placed on the struct itself:
context
Pass a validation context to custom validators:
use ;
let form = Form ;
let ctx = MyContext ;
form.validate_with_args;
mutable
Allow mutable access to the context:
nest_all_fields
Automatically validate all nested structs:
use Validate;
schema
Add struct-level validation functions:
use ;
Schema options:
function = path::to::fn- The validation functionskip_on_field_errors = false- Run even if field validation failed (default: true)
Field-Level Attributes
These attributes are placed on struct fields using #[validate(...)]:
Format Validators
| Attribute | Description | Options |
|---|---|---|
email |
Valid email address | message, code |
url |
Valid URL | message, code |
phone_number |
Valid phone number | country, message, code |
credit_card |
Valid credit card (Luhn) | message, code |
ip |
Valid IP address | format ("v4"/"v6"), message, code |
non_control_character |
No control characters | message, code |
regex |
Matches regex pattern | path, message, code |
Numeric Validators
| Attribute | Description | Options |
|---|---|---|
range |
Numeric range | min, max, exclusive_min, exclusive_max, message, code |
length |
String/collection length | min, max, equal, message, code |
Presence Validators
| Attribute | Description | Options |
|---|---|---|
required |
Field must be Some | message, code |
required_if |
Required if condition | func, message, code |
required_with |
Required if any field present | other_fields(...), message, code |
required_with_all |
Required if all fields present | other_fields(...), message, code |
required_without |
Required if any field absent | other_fields(...), message, code |
required_without_all |
Required if all fields absent | other_fields(...), message, code |
Prohibition Validators
| Attribute | Description | Options |
|---|---|---|
prohibited_if |
Must be None if condition | func, message, code |
prohibited_with |
Must be None if any field present | other_fields(...), message, code |
prohibited_with_all |
Must be None if all fields present | other_fields(...), message, code |
prohibited_without |
Must be None if any field absent | other_fields(...), message, code |
prohibited_without_all |
Must be None if all fields absent | other_fields(...), message, code |
Container Validators
| Attribute | Description | Options |
|---|---|---|
contains |
Contains value | pattern, message, code |
does_not_contain |
Doesn't contain value | pattern, message, code |
Comparison Validators
| Attribute | Description | Options |
|---|---|---|
must_match |
Equals another field | other, message, code |
Consent Validators
| Attribute | Description | Options |
|---|---|---|
accepted |
Boolean true or accepted string | message, code |
declined |
Boolean false or declined string | message, code |
accepted_if |
Accepted if condition | function, message, code |
declined_if |
Declined if condition | function, message, code |
Other Validators
| Attribute | Description | Options |
|---|---|---|
custom |
Custom validation function | function, use_context, message, code |
nested |
Validate nested struct | - |
skip |
Skip this field | - |
Multiple Validators
Apply multiple validators to a single field:
use Validate;
# use LazyLock;
# use Regex;
# static USERNAME_RE: = new;
Or combine in a single attribute:
use Validate;
Option, Option<Option<T>>, and Delta<T> Handling
The derive macro automatically handles optional fields:
Option<T>
None→ Validation skipped (unlessrequired)Some(value)→ Validate the inner value
Option<Option<T>> (PATCH semantics)
For partial update operations, the macro auto-detects Option<Option<T>>:
None→ Field omitted, validation skippedSome(None)→ Clearing field, validation skippedSome(Some(value))→ Validate the inner value
This affects cross-field validators like required_with:
use Validate;
// Clearing area_id - country_id NOT required
let update = UpdateAddress ;
assert!;
// Setting area_id - country_id IS required
let update = UpdateAddress ;
assert!;
Delta<T> (Recommended for PATCH)
Delta<T> from the delta crate is a three-state enum (Unchanged / Clear /
Set(value)) that provides the same semantics as Option<Option<T>> with less
boilerplate. The derive macro automatically recognizes Delta<T> and treats
only Delta::Set(_) as a value to validate.
use Delta;
use Deserialize;
use Validate;
Why use Delta<T> over Option<Option<T>>?
Option<Option<T>> |
Delta<T> |
|---|---|
Requires #[serde(default, deserialize_with = "...")] |
Only #[serde(default)] |
| No helper methods | is_unchanged(), is_clear(), is_set(), value() |
Nested Some(Some(_)) patterns |
Delta::Set(_) patterns or helper methods |
Semantics (identical for both types):
| State | Option<Option<T>> |
Delta<T> |
Validators |
|---|---|---|---|
| Absent | None |
Delta::Unchanged |
Skipped |
| Null | Some(None) |
Delta::Clear |
Skipped |
| Value | Some(Some(v)) |
Delta::Set(v) |
Run |
Custom Validators
Basic Custom Validator
use ;
Custom Validator with Context
use ;
Generated Code
For a struct like:
use Validate;
The macro generates approximately:
Error Messages and Codes
All validators accept message and code parameters:
use Validate;
Feature Flags
The derive macro respects the feature flags from the valid8r crate:
email- Email validation with IDN supporturl- URL validationphone_number- Phone number validationcards- Credit card validation
Implementation Details
This crate uses:
darlingfor attribute parsingsynfor Rust syntax parsingquotefor code generationproc-macro2for token manipulation
The macro generates both impl Validate and impl ValidateArgs to support
validation with and without context.
License
Licensed under either MIT or Apache License, Version 2.0, at your option. The MIT license includes the original upstream copyright notice.