validate derive feature

Learn what the derive feature of the validator crate switches on, how the Validate derive macro writes checking code for a struct, and how the Validate trait and its validate method work

The derive feature is a switch in the validator crate that turns on the Validate derive macro. With the switch on, you write #[derive(Validate)] above a struct and the compiler generates the code that checks the struct's fields. With the switch off, the trait still exists, but the macro does not, and the derive line fails to compile.

Where This Fits

The validator crate page added the crate to Cargo.toml with features = ["derive"] and showed one rule working. That page treated the derive line as a given. This page opens it up: what the feature actually switches on, what code the macro writes for you, and what the Validate trait promises once that code exists.

Think of the feature as a power switch for a machine in a workshop. The validator crate is the workshop. The Validate trait is a workbench that is always there. The derive macro is a machine that only runs when its switch is on, and when it runs it builds the checking code for each struct automatically.

The Smallest Working Version

The smallest example is a struct with one field and one rule, plus a main that calls validate() and prints the result.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
validator = { version = "0.21", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
}

fn main() {
    let signup = Signup {
        email: "ada@example.com".to_string(),
    };
    match signup.validate() {
        Ok(()) => println!("valid"),
        Err(errors) => println!("invalid: {:?}", errors),
    }
}

Running cargo run prints valid. Change the address to "not-an-email" and run it again, and the output becomes a long invalid: line holding the ValidationErrors value. The match here is the honest way to handle the result: Ok(()) means every rule passed, and Err(errors) carries the map of failures. A match forces you to handle both arms, so a failing value can never slip past silently.

Working Setup:

If cargo run prints valid for the good address and an invalid: line for the bad one, the derive macro is generating the Validate implementation and the trait method is running it.

What a Feature Is

A feature is a named option inside a crate's own Cargo.toml. Crate authors mark parts of their code as belonging to a feature, and that code is only compiled when somebody switches the feature on. The mechanism exists because not every user needs every part. A crate that offers ten validators might keep the credit card validator behind a feature, so projects that never check card numbers do not compile that code or its dependencies.

The validator crate follows the same shape. Its core holds the Validate trait, the error types, and the checking functions. The derive feature holds the derive macro and the code that reads #[validate(...)] attributes. Switching the feature on in your Cargo.toml tells Cargo to compile that extra code and make the macro available to your project.

Features are additive. Switching one on never switches another off, and two crates in the same project that ask for different features of the same dependency get the union of both. If one part of your project needs derive and another needs a different validator feature, Cargo enables both.

The Derive Macro, Piece by Piece

The line #[derive(Debug, Validate)] looks small, but three things happen when the compiler reads it. Each one is worth understanding, because the errors you meet later point at one of the three.

First, the compiler sees the derive keyword and knows a macro must generate code for this struct. A derive macro is a function that runs at compile time. It receives the struct definition as input, the field names and their attributes included, and it returns Rust code as output. That output is compiled as if you had written it by hand in the same file.

Second, the macro looks for the name Validate among the derive macros available to the project. That name only exists when the derive feature is on. The macro lives in a helper crate that the validator crate pulls in under that feature, and Cargo only compiles that helper when the feature is switched on. This is the step that fails with "cannot find derive macro Validate in this scope" when the feature is missing.

Third, the macro reads every #[validate(...)] attribute on the struct's fields and generates one validate() method that runs them all. The generated method checks each field in turn, collects every failure into a ValidationErrors map, and returns Ok(()) when the map is empty. You never see this generated code in your editor, but it behaves exactly like hand-written code that runs each check and gathers the errors.

The Debug derive next to Validate is unrelated to validation. It generates the code that lets the struct print with {:?}, which is what the examples use to show results. A struct can derive Validate without Debug, but then you cannot print it that way.

Generated Code Is Ordinary Code:

The code a derive macro writes is ordinary Rust code, compiled with the same checks as code you write by hand. If a rule does not fit its field, the compiler reports the error against your struct definition, even though the bad code was generated. That is why a type error from a rule points at the attribute line.

The Validate Trait and Its One Method

Once the macro has run, the struct implements the Validate trait. The trait itself is small. Its full definition, taken from the validator crate docs for version 0.21, is this.

pub trait Validate {
    fn validate(&self) -> Result<(), ValidationErrors>;
}

A trait is a promise that a type provides certain methods. This trait promises exactly one method, validate(). The method takes &self, which is a shared reference to the struct, so calling it does not consume the struct or change it. It returns Result<(), ValidationErrors>. The Ok side holds (), the unit value, which means "valid, and there is nothing to give back". The Err side holds a ValidationErrors value, which is the map of field errors.

The &self receiver matters for how you use the method. Because validation only reads the struct, you can call validate() on a value you still need afterwards. The handler pattern on a later page relies on this: the handler validates the input, and when validation passes, the same input value goes on to be used. Nothing is moved away or used up by the check.

The trait also has a companion trait called ValidateArgs, which the derive macro implements when a custom validator needs an extra argument. The plain Validate trait is the one you meet in normal use. Its validate() call forwards to the companion trait with a default empty argument, so you never have to think about the companion unless you write a custom validator that takes arguments. That case is outside this page, and the plain trait covers everything the following pages do.

What the Macro Generates for a Two-Field Struct

Reading generated code is hard because you never see it, so it helps to picture what the macro writes for a small struct. For this struct, the generated validate() method behaves like this hand-written version.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
}

fn main() {
    let signup = Signup {
        email: "ada@example.com".to_string(),
        name: "Ada".to_string(),
    };
    println!("{:?}", signup.validate());
}

The macro generates, in effect, a method that runs the email check on the email field and the length check on the name field, pushes any failure into a map under the field's name, and returns the map as an Err when it is not empty. The real generated code is longer and uses the crate's internal helpers, but its behaviour matches that description exactly. The order the fields are checked in is the order they appear in the struct, though the order of entries in the resulting map is not guaranteed, because the map is a hash map.

Two details of the generated code deserve attention. The first is that every field is checked even when an earlier field already failed. The generated method does not return early. It keeps going, so one call reports every problem. The second is that a field with no #[validate(...)] attribute gets no check at all. The macro only generates checks for fields that carry an attribute, so an unmarked field passes silently whatever value it holds.

The Import and the Trait Must Both Be Present

Two separate things have to be true before signup.validate() compiles. The struct must implement the Validate trait, which the derive macro provides, and the trait must be in scope where the method is called, which the use validator::Validate; line provides. Missing either one produces a different error, and telling them apart saves time.

When the derive macro is missing because the feature is off, the error is about the derive macro itself.

error: cannot find derive macro `Validate` in this scope
note: `Validate` is a trait, not a derive macro

When the derive macro ran but the import is missing, the error is about the method.

error: no method named `validate` found for struct `Signup` in the current scope
note: the following trait defines an item `validate`, perhaps you need to implement it

The compiler is pointing at the exact gap in each case. The first error says the macro does not exist, so fix the feature in Cargo.toml. The second says the trait exists but is not in scope, so add the use line. Both errors were reproduced against validator 0.21.0 while checking the examples for this page.

Two Different Errors, Two Different Fixes:

"Cannot find derive macro" means the derive feature is off, so fix Cargo.toml. "No method named validate" with the trait named in the note means the use validator::Validate; line is missing, so fix the import. Changing Rust code never fixes the first error, and changing Cargo.toml never fixes the second.

A Struct Without Rules Still Compiles

A struct that derives Validate but carries no #[validate(...)] attributes at all still gets a working validate() method. The generated method simply has nothing to check, so it always returns Ok(()).

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Notes {
    body: String,
}

fn main() {
    let notes = Notes {
        body: "anything at all".to_string(),
    };
    println!("{:?}", notes.validate());
}

The output is Ok(()) for any value of body. This is not a bug. The derive macro generates checks only for marked fields, and a struct with no marked fields has no checks. The behaviour is worth knowing because it explains a confusing moment: a struct that "should" fail validation passes, and the cause is a missing attribute rather than a broken rule. The fix is to add the attribute to the field that needs a rule.

Derive on Structs with Several Field Types

The macro works on any struct whose fields are types the rules can check. Strings, numbers, and Option fields all appear in the examples on the following pages, and the macro handles each one. A field of type Option<String> with an email rule is only checked when it holds Some value. A None value skips the rule entirely and passes, because there is no value to check. The required rule exists for the case where None itself should fail, and it is covered on the attributes page.

The macro also works when the struct derives Deserialize alongside Validate, which is the normal shape for data that arrives as JSON. The two derives do not interfere, because each one reads the struct definition and generates its own separate implementation. The order they are listed in does not matter.

src/main.rs
use serde::Deserialize;
use validator::Validate;

#[derive(Debug, Deserialize, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
}

fn main() {
    let signup = Signup {
        email: "ada@example.com".to_string(),
        name: "Ada".to_string(),
    };
    println!("{:?}", signup.validate());
}

This struct can be built from JSON by serde and checked by validator, using the same field definitions for both jobs. The Deserialize derive does not need validator, and the Validate derive does not need serde. A struct that is only ever built in code, never from JSON, can derive Validate alone and skip serde entirely.

Validate Does Not Need Deserialize:

#[derive(Validate)] works on a struct with no serde derive at all. If a struct is only built inside your program, leave serde off. Adding Deserialize is only needed when the struct arrives as JSON or another serialized format.

What Happens When the Struct Changes

A struct rarely stays the same shape forever. A new field is added, a rule is tightened, a field is renamed. The derive macro makes each of those changes safe, because it reads the struct fresh on every build.

Adding a field with a rule is one line: the field, its type, and its attribute. The generated validate() method picks the new check up with no other change. Adding a field without a rule is also one line, and the new field is simply unchecked until somebody writes a rule for it. That visibility is the point: an unchecked field is visible in the struct definition, not hidden in a missing if statement somewhere else.

Renaming a field keeps its rule attached, because the rule sits above the field and moves with it. The error map changes with the rename, since the map is keyed by field name, so a client that reads errors by field name sees the new name. That is a real consequence worth knowing: renaming a field is a change to the error response as well as to the struct, and any client that matches on field names needs the new name too.

Tightening a rule, such as changing length(min = 3) to length(min = 5), changes only the attribute. The generated code changes with it, and the tests that check boundary values catch the new behaviour. The shape of the code never changes, only the numbers inside the attributes.

What the Derive Feature Does Not Do

The feature switches on the macro and nothing else. It does not change how Axum handles requests, it does not register the struct anywhere, and it does not make validate() run on its own. A struct that derives Validate and is used as a Json extractor is still only deserialized by Axum. The validation call has to be written by hand, in the handler or in a custom extractor, and those call sites are the subject of the pages that follow this one.

The feature also does not add new rules. The set of rules, email, length, range, required, and the rest, is fixed by the validator crate itself. The feature only decides whether the macro that applies those rules is available. Adding a feature never invents a validator that the crate does not already provide.

The Flow from Attribute to Result

The whole mechanism fits in one short flow.

#[derive(Validate)] on the struct
        |
        v
Macro reads each #[validate(...)] attribute
        |
        v
Macro generates impl Validate with validate()
        |
        v
Code calls signup.validate()
        |
        v
validate() runs every rule, collects failures
        |
        v
Ok(()) when nothing failed, Err(ValidationErrors) otherwise

The first three steps happen at compile time, before the program ever runs. The last three happen at runtime, each time validate() is called. The compile-time part is why a mistake in an attribute is a compile error rather than a runtime surprise: the macro reads the attribute while the program is being built, and a rule it cannot understand stops the build.

Testing It

The derive macro is best tested by checking that validate() behaves as the attributes promise. These tests need no server. Each one builds a struct and asserts on the result of the call.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_signup_passes() {
        let signup = Signup {
            email: "ada@example.com".to_string(),
            name: "Ada".to_string(),
        };
        assert!(signup.validate().is_ok());
    }

    #[test]
    fn invalid_signup_reports_both_fields() {
        let signup = Signup {
            email: "not-an-email".to_string(),
            name: "Al".to_string(),
        };
        let errors = signup.validate().unwrap_err();
        let fields = errors.field_errors();
        assert!(fields.contains_key("email"));
        assert!(fields.contains_key("name"));
    }

    #[test]
    fn unmarked_struct_always_passes() {
        #[derive(Debug, Validate)]
        struct Notes {
            body: String,
        }
        let notes = Notes {
            body: "anything".to_string(),
        };
        assert!(notes.validate().is_ok());
    }
}

The second test is the important one for this page. It proves the generated method runs every rule instead of stopping at the first failure, because both email and name appear in the error map after a single call. The third test pins down the empty-struct behaviour: a struct with no attributes always passes. Run the tests with cargo test and expect three passes.

The tower crate is not needed for these tests, because no HTTP request is involved. It appears on later pages, where tests send requests through a router.

Common Beginner Mistakes

Forgetting the Feature

# Wrong - the macro is not compiled
validator = "0.21"

This is the most common mistake with this crate, and the error message does not mention features at all. It says the derive macro cannot be found and notes that Validate is a trait. The fix is one entry in Cargo.toml.

validator = { version = "0.21", features = ["derive"] }

After changing Cargo.toml, run cargo build again. Cargo notices the feature change and compiles the macro support. No Rust code needs to change.

Importing the Trait in the Wrong File

// Wrong - the use line is in main.rs, the call is in handlers.rs
// handlers.rs
async fn create_signup(Json(input): Json<Signup>) -> Json<Signup> {
    input.validate().unwrap();
    Json(input)
}

Rust imports are per file, not per project. A use validator::Validate; line in main.rs does not make the trait available in handlers.rs. Each file that calls .validate() needs its own import. The compiler error names the struct and the missing method, and the fix is the import in the file that makes the call. This bites in Axum projects because the struct is often defined in one module and validated in a handler module.

Deriving Validate on an Enum

// Wrong - the derive macro only works on structs
#[derive(Debug, Validate)]
enum Colour {
    Red,
    Green,
}

The Validate derive macro only supports structs. Applying it to an enum fails to compile, because the macro reads field attributes and enums have variants instead of fields. If an enum needs checking, the check belongs in ordinary code. Structs are the shape validation is built for, because a struct is a fixed set of named fields and each field can carry its own rule.

Expecting validate to Borrow the Struct Away

// Wrong - validate() takes &self, so this compiles, but the worry is misplaced
let signup = Signup { email: "ada@example.com".to_string(), name: "Ada".to_string() };
signup.validate().unwrap();
println!("{:?}", signup);

This code actually compiles and runs fine, and it is shown here because beginners often expect the opposite. The validate() method takes &self, a shared reference, so the struct is still owned by the caller after the call. The println! after the check works. The mistake is the assumption, not the code: validation never consumes the value it checks.

Final Complete Example

Here is everything from this page put together: the dependency with the feature switched on, a struct with two rules, a main that handles both outcomes of validate(), and the tests that prove the generated method checks every field.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
validator = { version = "0.21", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
}

fn main() {
    let good = Signup {
        email: "ada@example.com".to_string(),
        name: "Ada".to_string(),
    };
    match good.validate() {
        Ok(()) => println!("good signup is valid"),
        Err(errors) => println!("good signup failed: {:?}", errors),
    }

    let bad = Signup {
        email: "not-an-email".to_string(),
        name: "Al".to_string(),
    };
    match bad.validate() {
        Ok(()) => println!("bad signup is valid"),
        Err(errors) => println!("bad signup failed: {:?}", errors),
    }
}

Running cargo run prints good signup is valid and then a bad signup failed: line listing both fields. The two rules ran in one call, and the result named every failure.

Summary

The derive feature is a small switch with a large effect: it turns a trait that already exists into a macro that writes the trait's implementation for you, reading the rules off the struct as it goes. The single most important insight is the split between compile time and runtime. At compile time the macro reads attributes and generates checking code, which is why attribute mistakes are compile errors. At runtime validate() is an ordinary method call that reads the struct, runs every rule, and hands back either nothing or a map of everything that failed. Once that split is clear, the rest of the group is just vocabulary: the names of the rules, the shape of the error map, and the places where the one-line call belongs.