Validy
But, also modification.
A powerful and flexible Rust library based on procedural macros for validation, modification, and DTO (Data Transfer Object) handling. Designed to integrate seamlessly with Axum. Inspired by Validator, Validify and Garde.
- 📝 Installation
- 🚀 Quick Start
- 🔎 Validation Flow
- 🎯 Work In Progress
- 🔌 Axum Integration
- 🧩 Manual Usage
- 🚩 Feature Flags
- 🚧 Validation Rules
- 🔨 Modification Rules
- 🔧 Special Rules
- 📐 Useful Macros
- 📁 More Examples
- 🎁 For Developers
📝 Installation
Add with Cargo:
cargo add validy --features axum,email
Or add this to your Cargo.toml:
[]
= { = "1.0.0", = ["axum", "email"] }
🚀 Quick Start
The main entry point is the #[derive(Validate)] macro. It allows you to configure validations, modifications, and payload behaviors directly on your struct.
use crate;
//-------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^ Well, it's my validation context.
// You will use your own when need pass a context.
use Deserialize;
use Arc;
use ;
// To pass a struct to nested validations, the struct needs `Default` derive.
// As a rule, the input is `(&field, &field_name)`.
// All custom rules also can be throw validation errors.
// Unfortunately, each modification has to return a new value, instead of changing the existing one.
// This ensures that changes are only commited at the end of the validation process.
// Custom functions can be async, instead sync.
// With context, or not. See `custom` and `custom_with_context`, `async_custom`,
// `async_custom_with_context` and `inline` rules.
async
🔎 Validation Flow
You might not like it, but I took the liberty of naming things as I want. So, first, lets me show my glossary:
//vvvvvvvv Configuration
//---------^^^^^^^^^^^^ Configuration attribute
Almost all rules are executed in order from left to right and from top to bottom, according to their role group and definitions.
There is a cost to commit changes after all the rules have been met. When the modify or payload configuration attributes are enabled, a new copy of the changed value will be created after each modification.
In contrast, no primitive rule is asynchronous, therefore the asynchronous configuration attribute is only necessary to enable custom rules. The use of context is similar.
🎯 Work In Progress
- [] Typed multipart/form-data validation support.
- Maybe file validation rules too.
🔌 Axum Integration
When enabling the axum feature the library automatically generates the FromRequest implementation for your struct with axum configuration attribute enabled. The automated flow:
- Extract: receives the JSON body.
- Deserialize: deserializes the body.
- When the
payloadconfiguration attribute is enabled, the body will be deserialized as awrapper. - The name of the
wrapperstruct is the name of thepayloadstruct with the suffix'Wrapper', for example:CreateUserDTOgenerates a publicwrappernamedCreateUserDTOWrapper. - The generated
wrapperis left exposed for you to use.
- When the
- Execute: executes all the
rules. - Convert: if successful, passes the final struct to the
handler. - Error Handling: if any step fails, returns
Bad Requestwith a structured list of errors.- When the
payloadconfiguration attribute is disabled, missing fields throwsUnprocessable Entity.
- When the
See an example:
pub async
Yes, it's beautiful.
🧩 Manual Usage
The derive macros implement specific traits for your structs. To call methods like .validate(), .async_validate(), or ::validate_and_parse(...), you must import the corresponding traits into your scope.
use ;
// Or just import the prelude
use *;
Available traits
| Category | Traits |
|---|---|
| Validation | Validate, AsyncValidate, ValidateWithContext<C>, SpecificValidateWithContext, AsyncValidateWithContext<C> and SpecificAsyncValidateWithContext. |
| Modification | ValidateAndModificate, AsyncValidateAndModificate, ValidateAndModificateWithContext<C>, SpecificValidateAndModificateWithContext, AsyncValidateAndModificateWithContext<C> and SpecificAsyncValidateAndModificateWithContext. |
| Parsing | ValidateAndParse<W>, SpecificValidateAndParse, AsyncValidateAndParse<W>, SpecificAsyncValidateAndParse, ValidateAndParseWithContext<W, C>, SpecificValidateAndParseWithContext, AsyncValidateAndParseWithContext<W, C> and SpecificAsyncValidateAndParseWithContext. |
| Error | IntoValidationError |
🚩 Feature Flags
Crate behavior can be adjusted in Cargo.toml.
| Feature | Description | Dependencies |
|---|---|---|
default |
derive, validation, modification |
|
all |
Enables all features. | |
derive |
Enables macro functionality. | serde, validation_derive |
validation |
Enables validation functions. Needed by almost all derive primitives validation rules. |
|
modification |
Enables modification functions. Needed by almost all derive primitives modification rules. |
heck |
email |
Enables email validation rule. |
email_address |
pattern |
Enables pattern and url validation rules. Uses moka to cache regex. Cache can be configured calling ValidationSettings::init(...). |
moka, regex |
ip |
Enables ipI'm a busy and currently not very successful graduate student, so don't expect too much from me in terms of maintenance. But I did my best. validation rule. |
|
time |
Enables time validation rules. | chrono |
axum |
derive | Enables axum integration. |
axum |
macro_rules |
Enables macros for validation errors. | |
macro_rules_assertions |
Enables macros for assertions (tests). | pretty_assertions |
🚧 Validation Rules
Primitive rules of #[validate(<rule>, ...)] rule group.
The '?' indicates that arg is optional.
For required fields
| Rule | Description |
|---|---|
required(message = <?string>, code = <?string>) |
Changes the default message and code displayed when a field is missing. Requires that payload configuration attribute is enabled. |
For string fields
| Rule | Description |
|---|---|
contains(slice = <string>, message = <?string>, code = <?string>) |
Validates that the string contains the specified substring. |
email(message = <?string>, code = <?string>) |
Validates that the string follows a standard email format. |
url(message = <?string>, code = <?string>) |
Validates that the string is a standard URL. Finding goods regex patterns for URLs is so difficult and tedious. I decided to use the pattern (http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*) related here. |
ip(message = <?string>, code = <?string>) |
Validates that the string is a valid IP address (v4 or v6). |
ipv4(message = <?string>, code = <?string>) |
Validates that the string is a valid IPv4 address. |
ipv6(message = <?string>, code = <?string>) |
Validates that the string is a valid IPv6 address. |
pattern(pattern = <regex>, message = <?string>, code = <?string>) |
Validates that the string matches the provided Regex pattern. |
suffix(suffix = <string>, message = <?string>, code = <?string>) |
Validates that the string ends with the specified suffix. |
prefix(prefix = <string>, message = <?string>, code = <?string>) |
Validates that the string starts with the specified prefix. |
length(range = <range>, message = <?string>, code = <?string>) |
Validates that the length (string or collection) is within limits. |
For collection or single fields
| Rule | Description |
|---|---|
length(range = <range>, message = <?string>, code = <?string>) |
Validates that the length (string or collection) is within limits. |
allowlist(mode = <"SINGLE" | "COLLECTION">, items = <array>, message = <?string>, code = <?string>) |
Validates that the value or collection items is present in the allowed list (allowlist). |
blocklist(mode = <"SINGLE" | "COLLECTION">, items = <array>, message = <?string>, code = <?string>) |
Validates that the value or collection items is NOT present in the forbidden list (blocklist). |
For numbers fields
| Rule | Description |
|---|---|
range(range = <range>, message = <?string>, code = <?string>) |
Validates that the number falls within the specified numeric range. |
For date or time fields
| Rule | Description |
|---|---|
time(format = <string>, message = <?string>, code = <?string>) |
Validates that the string matches the specified DateTime<FixedOffset> format. Not parse the string. |
naive_time(format = <string>, message = <?string>, code = <?string>) |
Validates that the string matches the specified NaiveDateTime format. Not parse the string. |
naive_date(format = <string>, message = <?string>, code = <?string>) |
Validates that the string matches the specified NaiveDate format. Not parse the string. |
after_now(accept_equals = <?bool>, message = <?string>, code = <?string>) |
Validates that the DateTime<FixedOffset> is strictly after the current time. |
before_now(accept_equals = <?bool>, message = <?string>, code = <?string>) |
Validates that the DateTime<FixedOffset> is strictly before the current time. |
now(ms_tolerance = <?int>, message = <?string>, code = <?string>) |
Validates that the DateTime<FixedOffset> matches the current time within a tolerance (default: 500ms). |
after_today(accept_equals = <?bool>, message = <?string>, code = <?string>) |
Validates that the NaiveDate is strictly after the current day. |
before_today(accept_equals = <?bool>, message = <?string>, code = <?string>) |
Validates that the NaiveDate is strictly before the current day. |
today(message = <?string>, code = <?string>) |
Validates that the `NaiveDate matches the current day. |
Custom rules
All with prefix async_ requires that asynchronous configuration attribute is enabled. And all with suffix _with_context requires that context configuration attribute is defined.
| Rule | Description |
|---|---|
inline(closure = <closure>, params = <?array>, message = <?string>, code = <?string>) |
Validates using a simple inline closure returning a boolean. |
custom(function = <function>, params = <?array>) |
Validates using a custom function. |
custom_with_context(function = <function>, params = <?array>) |
Validates using a custom function with access to the context. |
async_custom(function = <function>, params = <?array>) |
Validates using a custom async function. |
async_custom_with_context(function = <function>, params = <?array>) |
Validates using a custom async function with access to the context. |
🔨 Modification Rules
Primitive rules of #[modify(<rule>, ...)] rule group. All requires that payload or modify configuration attributes are enabled.
The '?' indicates that arg is optional.
For string fields
| Rule | Description |
|---|---|
trim |
Removes whitespace from both ends of the string. |
trim_start |
Removes whitespace from the start of the string. |
trim_end |
Removes whitespace from the end of the string. |
uppercase |
Converts all characters in the string to uppercase. |
lowercase |
Converts all characters in the string to lowercase. |
capitalize |
Capitalizes the first character of the string. |
camel_case |
Converts the string to CamelCase (PascalCase). |
lower_camel_case |
Converts the string to lowerCamelCase. |
snake_case |
Converts the string to snake_case. |
shouty_snake_case |
Converts the string to SHOUTY_SNAKE_CASE. |
kebab_case |
Converts the string to kebab-case. |
shouty_kebab_case |
Converts the string to SHOUTY-KEBAB-CASE. |
train_case |
Converts the string to Train-Case. |
For date or time fields
All these rules was created to be used with the special rule #[special(from_type(String))] before.
| Rule | Description |
|---|---|
parse_time(format = <string>, message = <?string>, code = <?string>) |
Validates and parses that the string matches the specified time/date format. |
parse_naive_time(format = <string>, message = <?string>, code = <?string>) |
Validates and parses that the string matches the specified naive time format. |
parse_naive_date(format = <string>, message = <?string>, code = <?string>) |
Validates and parses that the string matches the specified naive date format. |
Custom rules
All with prefix async_ requires that asynchronous configuration attribute is enabled. And all with suffix _with_context requires that context configuration attribute is defined.
| Rule | Description |
|---|---|
inline(closure = <closure>, params = <?array>) |
Modifies the value using an inline closure. |
custom(function = <function>, params = <?array>) |
Modifies the value in-place using a custom function. |
custom_with_context(function = <function>, params = <?array>) |
Modifies the value in-place using a custom function with context access. |
async_custom(function = <function>, params = <?array>) |
Modifies the value in-place using a custom async function. |
async_custom_with_context(function = <function>, params = <?array>) |
Modifies the value in-place using a custom async function with context access. |
🔧 Special Rules
Primitive rules of #[special(<rule>, ...)] rule group.
The '?' indicates that arg is optional.
| Rule | Description |
|---|---|
nested(value = , wrapper = <?type>) |
Validates the fields of a nested struct. Warning: cyclical references can cause many problems. |
for_each(config?(from_item = <?type>, to_collection = <?type>, from_collection = <?type>), <rule>) |
Applies validation rules to every element in a collection. The arg from_item from optional config rule defines the type of each item of the collection. The arg to_collection defines the final type of the collection and the arg from_collection defines de initial type of the collection. Just from_type adapters to collections. |
from_type(value = <?type>) |
Need to be defined above and first all others rules. |
📐 Useful Macros
Sometimes, you might prefer to use macros to declare errors or assertions.
For errors
All requires that macro_rules feature flag is enabled.
// SimpleValidationError
let error = validation_error!;
// SimpleValidationError
let error = validation_error!;
// ValidationErrors
let errors = validation_errors! ;
// NestedValidationError
let error = nested_validation_error!;
For assertions
All requires that macro_rules_assertions feature flag is enabled.
let mut wrapper = default;
let mut result = validate_and_parse;
assert_errors!;
let result = test.validate_and_modificate;
assert_validation!;
assert_modification!;
result = validate_and_parse;
assert_parsed!;
📁 More Examples
If you need more references, you can use the /tests as an example.
🎁 For Developers
Well... You can run all tests with cargo test-all and see the derive macros's implementations running the script expand.sh (requires cargo expand). It will compile, generate and check all tests. I hope.
I'm a busy and currently not very successful graduate student, so don't expect too much from me in terms of maintenance. But I did my best.