valid8r
Validate Rust structs with #[derive(Validate)] and receive structured field,
nested, and schema errors. Use it for form input, API payloads, and partial
updates.
This crate builds on validator by
Vincent Prouillet and its contributors. It adds conditional presence and
prohibition rules, phone and consent validation, PATCH semantics.
Contents
- Quick Start
- Feature Flags
- Error Handling
- Optional Fields
- Sensitive Values
- PATCH Semantics
- Nested Validation
- Custom Validators
- Schema Validation
- Validation Context
- Custom Error Messages and Codes
- Skipping Fields
- Request Validation
- Validator Reference
- License
Quick Start
Requires Rust 1.94 or later. Add this to Cargo.toml:
[]
= "0.2"
The Validate import brings both the derive macro and the trait into scope.
Annotate fields with rules, then call .validate():
use Validate;
let mut signup = SignUp ;
assert!;
signup.email = "invalid".into;
let errors = signup.validate.unwrap_err;
assert_eq!;
Validation returns Ok(()) when all rules pass and Err(ValidationErrors)
when they fail. It checks the values without changing them. You must call
.validate() yourself after constructing or deserializing the struct.
Feature Flags
The derive macro is always available. No optional features are enabled by default. Basic email, length, range, IP, presence, consent, and custom rules work with the dependency above.
Enable email when you need email domain syntax checks. Without this
feature, email checks the local part and lengths but can accept an empty
or malformed domain, such as "person@".
| Feature | What it adds |
|---|---|
email |
Email domain validation through idna; basic email validation is already available |
url |
HTTP/HTTPS URL validation |
phone_number |
Phone validation through phonenumber |
cards |
Credit-card validation through card-validate |
indexmap |
length validation for IndexMap and IndexSet |
full |
All optional features above |
Enable the features your fields need:
[]
= { = "0.2", = ["url", "phone_number"] }
For all optional validators, use features = ["full"]. A rule such as
#[validate(url)] needs its feature enabled in Cargo.toml.
Error Handling
Each ValidationError has a machine-readable code, an optional message,
and a params map with details such as the submitted value and rule bounds.
The default code is usually the validator name, for example "email" or
"length". Messages are only present when supplied by an attribute or a
custom validator.
Use .field_errors() to inspect direct field errors:
use Validate;
let contact = Contact ;
let errors = contact.validate.unwrap_err;
let error = &errors.field_errors;
assert_eq!;
assert_eq!;
assert_eq!;
// Serialize the whole error tree for an API response.
let json = to_value.unwrap;
assert_eq!;
Add serde_json = "1" to your application's dependencies for serialization.
The JSON representation of the error above is:
.field_errors() includes only direct field errors. Use .errors() or
serialize the whole ValidationErrors to retain nested errors. Entries are
ValidationErrorsKind::Field (a list of errors), Struct (child fields), or
List (child errors indexed by position). Schema errors use the __all__
key. See Nested Validation and
Schema Validation.
When scalar field errors and nested errors share a key, the nested errors take precedence and the scalar errors under that key are discarded.
Optional Fields
Value rules such as email, length, range, and custom check the inner
value of Some(value) and skip None. Add required when the value must be
present (or just don't make it Option):
use Validate;
let missing = Profile ;
assert_eq!;
let present = Profile ;
assert!;
required checks presence, rather than string length: Some("") satisfies
required, but fails length(min = 1). Presence and prohibition rules still
check absent fields; they do not behave like value rules.
Empty Strings
email(nullable), url(nullable), and phone_number(nullable) accept an
empty string as well as a valid value. They leave the empty string unchanged;
conversion to
None or a database null belongs to your application.
use Validate;
let empty = Contact ;
let invalid = Contact ;
assert!;
assert!;
Enable the corresponding url or phone_number feature for those rules.
Whitespace is not an empty string, and nullable does not bypass other
rules on the field.
Sensitive Values
Value validators normally include the submitted value in error parameters.
Add sensitive to a field to remove its value parameter. When must_match
compares against a sensitive field, it also omits that field's other
parameter:
use Validate;
let change = PasswordChange ;
let errors = change.validate.unwrap_err;
assert!;
assert!;
assert!;
Codes, messages, and non-value parameters such as min remain available.
Custom validators control their other parameters and messages, so keep
credentials out of those too. Annotate sensitive fields inside nested structs
as well; an annotation on a parent field does not redact its children's
errors.
PATCH Semantics
Partial updates need three states: leave a field unchanged, clear it, or set
it to a value. valid8r recognizes both Option<Option<T>> and
Delta<T>.
| Request state | Option<Option<T>> |
Delta<T> |
Value rules run? | Counts as present? |
|---|---|---|---|---|
| Omitted | None |
Delta::Unchanged |
No | No |
Explicit null |
Some(None) |
Delta::Clear |
No | No |
| Value | Some(Some(value)) |
Delta::Set(value) |
Yes | Yes |
Presence rules still run. For example, required rejects both omitted and
cleared fields, while required_with becomes active only when a referenced
field has an actual value. valid8r validates the incoming update; applying
it to stored data is your application's responsibility.
Using Option<Option<T>>
Serde's default handling of nested Options treats both a missing field and
JSON null as None. Use default together with a custom deserializer to
preserve explicit nulls. For the example below, add:
[]
= { = "1", = ["derive"] }
= "1"
use ;
use Validate;
let omitted: UpdateUser = from_str.unwrap;
assert_eq!;
assert!;
let cleared: UpdateUser = from_str.unwrap;
assert_eq!;
assert!;
// Setting area_id requires a value for country_id too.
let missing_country: UpdateUser = from_str.unwrap;
assert!;
let valid: UpdateUser =
from_str.unwrap;
assert!;
Using Delta<T>
Delta<T> models the same states directly and requires only
#[serde(default)] for missing fields. Use the delta repository below;
the unrelated crate with the same name on crates.io does not provide this
type:
[]
= { = "https://github.com/musajingo/delta", = "v0.1.0" }
= { = "1", = ["derive"] }
= "1"
use Delta;
use Deserialize;
use Validate;
let cleared: UpdateUser = from_str.unwrap;
assert!;
assert!;
let invalid: UpdateUser = from_str.unwrap;
assert!;
Nested Validation
Validate nested structs using the nested attribute:
use Validate;
Use nest_all_fields when every field should receive nested validation. Each
field must support .validate() after unwrapping any optional values:
use Validate;
#
#
Use #[validate(nested)] on Vec<T> to validate its elements. Child errors
remain under the parent field; collection errors are indexed by element
position. Optional nested values are skipped when absent. For example:
use ;
let order = Order ;
let errors = order.validate.unwrap_err;
let List = &errors.errors else ;
assert_eq!;
Custom Validators
Use a custom function for validation. Multiple custom validators can be applied.
use ;
The function returns Ok(()) for a valid value or a ValidationError for an
invalid value. Optional fields pass their inner value when present. Numeric
primitives written as i32, f64, etc. are passed by value; aliases and
qualified spellings can instead require references. Strings and collections
can use borrowed arguments such as &str and &[T]. Values passed to custom
field validators must support Serde serialization so they can be recorded
in error parameters.
Schema Validation
Use a schema function for a rule involving the whole struct. It receives
&Struct and returns Result<(), ValidationError>:
use ;
let invalid = DateForm ;
let errors = invalid.validate.unwrap_err;
assert_eq!;
// Field errors skip this schema function by default.
let invalid_field = DateForm ;
assert!;
Schema errors are stored under __all__. By default, schema functions run
only when field validation, including nested validation, passes. Add
skip_on_field_errors = false to the schema attribute to run it despite
field errors:
#[validate(schema(function = check_date_range, skip_on_field_errors = false))].
You can repeat the #[validate(schema(...))] attribute to run multiple
functions. An earlier schema failure does not suppress later schemas when
all fields were valid. Use use_context to pass a
validation context along with the struct.
Validation Context
Use ValidateArgs to pass application data into a custom field or schema
validator. Declare its type on the struct and add use_context to each
function that needs it:
use ;
let ctx = ValidationContext ;
let order = Order ;
let errors = order.validate_with_args.unwrap_err;
assert_eq!;
A struct with context uses .validate_with_args(&ctx) instead of generating
an argument-free .validate(). Schema functions with use_context receive
(&Struct, &Context). For a context type containing borrowed data, use the
lifetime 'v_a in its attribute path, for example
#[validate(context = "ValidationContext<'v_a>")]. Add mutable at the struct
level when the context must be passed as &mut Context.
Nested validation calls each child's .validate(); it does not forward
the parent's context automatically.
Custom Error Messages and Codes
Value, presence, consent, custom, and schema rules accept code and
message. Keep codes stable for callers; use messages for display:
use Validate;
Skipping Fields
Skip validation for specific fields:
use Validate;
Fields without validation attributes are otherwise left alone. skip is
useful when opting out of struct-wide nest_all_fields validation.
Request Validation
In a web handler, deserialize the payload, validate it, and then perform the
operation. Deserialization and validation report different failures: JSON
parsing checks types and syntax, while .validate() checks your rules.
The following function can be called from a handler in any web framework.
For this example, add serde with its derive feature and serde_json as
shown in PATCH Semantics.
use Deserialize;
use ;
assert!;
assert!;
assert!;
Map InvalidJson and InvalidFields to your framework's error responses.
Serialize the ValidationErrors in InvalidFields when returning field
feedback to a client.
Validator Reference
Rules can share a single attribute, such as
#[validate(required, email)], or use separate attributes on the same field.
custom can be repeated to call multiple functions.
| Group | Rules |
|---|---|
| String/format | email, url, phone_number, credit_card, ip, regex, non_control_character |
| Numeric and length | range, length |
| Presence | required, required_if, required_with, required_with_all, required_without, required_without_all |
| Prohibition | prohibited_if, prohibited_with, prohibited_with_all, prohibited_without, prohibited_without_all |
| Containers | contains, does_not_contain |
| Comparison | must_match |
| Consent | accepted, declined, accepted_if, declined_if |
| Custom | custom |
Presence and prohibition rules interpret Some(_) as present for Option<T>,
and only actual inner values as present for PATCH types. With an empty
string, an Option<String> is still present. Fields named in other_fields
must be optional (Option<T>, nested Option, or Delta<T>). Predicate
functions for required_if and prohibited_if receive &Struct and return
bool.
String/Format Validators
email
Checks for an @, a nonempty local part matching the supported character
pattern, and length limits of 64 Unicode scalar values for the local part
and 255 for the domain. The email feature additionally checks domain
syntax, including internationalized domains and supported IP literals.
It does not verify that a mailbox or domain exists.
use Validate;
let newsletter = Newsletter ;
assert!;
let invalid = Newsletter ;
assert!;
Supported types: String, &str, Cow<str>, Option<T> where T implements ValidateEmail
url
Validates an absolute HTTP or HTTPS URL. Other schemes, including ftp:,
javascript:, and data:, are rejected.
#
#
Requires: the url cargo feature (not in the default set)
phone_number
Parses phone numbers and checks their validity using phonenumber. The
optional country is a parsing hint for national-format numbers, not a
restriction on international numbers with an explicit country prefix.
#
#
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
Checks credit-card format and checksum through card-validate. Passing
validation does not establish that a card is active or can be charged.
#
#
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 Regex;
use LazyLock;
use Validate;
// Define regex as a static for efficiency
static USERNAME_RE: =
new;
Add regex = "1" to your dependencies. A LazyLock compiles the pattern once
and reuses it for each validation.
non_control_character
Validates that a string contains no control characters.
use Validate;
Numeric and Length Validators
range
Validates that a number falls within a specified range.
Inclusive bounds alone do not reject floating-point NaN. Use a custom
validator that checks .is_finite() when non-finite values must be rejected.
use Validate;
let mut product = Product ;
assert!;
product.probability = 1.0;
assert!;
# product.probability = 0.5;
# product.price = f64NAN;
# assert!;
Supported types: All numeric primitives (u8-u128, i8-i128, usize, isize, f32, f64),
rust_decimal::Decimal, Option<T>, Option<Option<T>>
length
Checks the number of Unicode scalar values in a string, or the number of
items in a collection or array. Bounds are inclusive. Use equal on its own;
it cannot be combined with min or max in a derive attribute.
use Validate;
Supported types: String, &str, Vec<T>, HashMap, HashSet, BTreeMap,
BTreeSet, VecDeque, [T; N], &[T], Cow<str>
For strings, this is the count from .chars(), rather than bytes or displayed
grapheme clusters. For example, a letter followed by a combining accent
counts as two scalar values.
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
The field is required if any of the specified fields have a value.
use Validate;
required_with_all
The field is required if all specified fields have values.
use Validate;
required_without
The field is required if any of the specified fields are missing.
use Validate;
required_without_all
The field is required if all specified fields are missing.
use Validate;
Prohibition Validators
prohibited_if
The field must be absent if a condition is met.
use Validate;
prohibited_with
The field must be absent if any of the specified fields have values.
use Validate;
prohibited_with_all
The field must be absent if all specified fields have values.
prohibited_without
The field must be absent if any of the specified fields are missing.
prohibited_without_all
The field must be absent 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 HashMap;
use Validate;
does_not_contain
Checks that a string does not contain a substring, or a supported map does not contain the specified key.
use Validate;
Comparison Validators
must_match
Compares a field with another field of the same underlying type. The check runs only when the annotated field has a value. If the other field is absent or cleared, a present value fails the comparison.
use Validate;
Consent Validators
accepted
Accepts true for booleans. For strings, accepts "true", "1", "on", or
"yes", ignoring ASCII case.
use Validate;
declined
Accepts false for booleans. For strings, accepts every value that accepted
rejects, including an empty string. It does not restrict input to a fixed
list of negative answers.
use Validate;
accepted_if / declined_if
Checks acceptance or decline when the predicate returns true. For an
Option<bool>, None skips this value check; add a required* rule when
absence should also fail.
use Validate;
License
Licensed under either MIT or Apache License, Version 2.0, at your option. The MIT license includes the original upstream copyright notice.