validator crate

Learn what the validator crate is, how to add it to an Axum project, and how declarative rules on a struct replace hand-written checks

The validator crate is a Rust library that checks the fields of a struct against rules you write on the struct itself. You describe what good data looks like once, right next to each field, and then one method call runs every rule and reports every problem it finds.

Where This Fits

The page on 422 responses with field errors showed a response shape that lists each bad field with its own message. That shape needs a source of field errors. Hand-written checks can produce it, but each check is a separate if statement that you write, order, and keep in step with the struct by hand. The validator crate is the tool that produces those field errors from rules instead of from hand-written checks.

Think of it like a checklist printed on a form. A hand-written check is a person reading the form and remembering each rule. The validator crate is the checklist itself, printed next to each box, so nothing is forgotten and every box is checked in the same way every time.

The Smallest Working Version

Start a new project or open the project you already have, and add one line to its dependencies. This is the whole setup for this page.

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"

The line that matters here is the validator line. The version 0.21 is the current release, and the derive feature switches on the part of the crate that writes checking code for your structs automatically. Without that feature the crate still exists, but the convenient derive macro does not.

Now write the smallest struct that uses it.

src/main.rs
use validator::Validate;

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

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

    let bad = Signup {
        email: "not-an-email".to_string(),
    };
    println!("bad: {:?}", bad.validate());
}

Run it with cargo run. The output is two lines.

good: Ok(())
bad: Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("not-an-email")} }])}))

The good address passes and validate() returns Ok(()), which is Rust's way of saying the value is fine and there is nothing to return. The bad address fails and validate() returns an Err holding a ValidationErrors value. That value is a map keyed by field name, so "email" points at a list with one ValidationError inside it. The code field says which rule failed, "email", and params holds the value that was checked.

Working Setup:

If cargo run prints good: Ok(()) and an Err line for the bad address, the validator crate is installed and working. The Err line is the expected result for bad input, not a crash.

What the Cargo.toml Line Means

The validator line has three parts, and each one does a separate job.

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

The name validator is the crate name on crates.io, the public registry where Rust libraries are published. The version = "0.21" entry tells Cargo to use the 0.21 release line. Cargo reads that as "0.21 or a later patch release that stays compatible", so it picks 0.21.0 or a later 0.21 patch if one exists. The features = ["derive"] entry switches on an optional part of the crate. A feature is a named switch in a crate's own Cargo.toml that turns extra code on or off. Here the derive feature turns on the Validate derive macro, the piece that reads the #[validate(...)] attributes and writes the checking code for you.

Serde appears in the dependencies because real Axum projects almost always combine the two crates. Serde turns JSON into structs, and validator checks those structs. The two jobs are separate. Serde answers "is this JSON shaped like my struct", and validator answers "are the values inside the struct acceptable". This page only needs validator, but the Cargo.toml above includes serde because every later example in this group of pages uses both together.

A Crate Is a Library:

A crate is Rust's word for a library or a package. When you write validator = "0.21" in Cargo.toml, Cargo downloads that library from crates.io the first time you build, compiles it, and links it into your program. You then bring its items into your files with use statements, exactly like use validator::Validate;.

The Three Pieces in the Small Example

The small example has three pieces that always appear together when you use this crate. They are worth naming now because every later example reuses them.

The first piece is the import. use validator::Validate; brings the Validate trait into scope. A trait is a set of methods that a type promises to provide. The Validate trait promises exactly one method, validate(), which takes a reference to the struct and returns Result<(), ValidationErrors>. Without this import, calling .validate() on your struct fails to compile, because Rust cannot see the method.

The second piece is the derive. #[derive(Debug, Validate)] sits above the struct and asks the compiler to generate code. Debug is a standard derive that lets the struct print with {:?}. Validate is the validator crate's derive macro. A derive macro is a small program that runs at compile time, reads your struct definition, and writes an implementation of a trait for it. Here it writes the Validate implementation, which is the code that runs each field's rules when validate() is called.

The third piece is the attribute. #[validate(email)] sits above a field and states one rule for that field. An attribute is a note attached to a piece of code that changes how the compiler or a macro treats it. The Validate derive macro reads these attributes and turns each one into a check. The word inside the parentheses names the rule. email means the string must look like an email address.

The Concept Behind the Crate

The idea behind validator is that rules belong with the data they guard. A signup form has an email field, and the rule "this must look like an email address" is a fact about that field. Writing the rule next to the field keeps the fact and the field together, so a reader sees both at once and a change to one is made next to the other.

The opposite shape is a pile of checks somewhere else in the code. Each check names a field, repeats its type in the condition, and builds its own error. The checks drift apart from the struct as the struct grows. A field gets renamed in the struct but not in the check. A new field gets added with no check at all. The compiler cannot catch either mistake, because the checks are ordinary code that happens to mention field names.

Rules written as attributes do not have that drift. The derive macro reads the struct as it exists right now. A renamed field keeps its rule, because the rule sits above the field. A new field with no attribute simply has no rule, which is visible at a glance. And the generated code runs every rule on every call, so no rule is skipped because an earlier if returned first.

One plain sentence draws the line against hand-written checks: hand-written checks are if statements you write and order yourself, while validator rules are notes on the struct that one call runs for you.

One Call Runs Every Rule

The most useful property of validate() is that it does not stop at the first failure. It runs every rule on every field, collects every failure, and returns them all at once in the ValidationErrors map. A signup form with a bad email, a short name, and a young age reports all three problems in a single call, so the user can fix all three before sending the form again.

This is different from a chain of if statements that returns on the first failure. That shape makes the user fix one field, send the form again, and learn about the next failure. Running every rule and reporting every failure is kinder to the user and simpler for the server, because one call produces the complete list.

The ValidationErrors value is a map from field name to a list of errors for that field. A field can fail more than one rule, so the value is a list rather than a single error. The map only holds fields that failed. Fields that passed do not appear at all, which is why checking validate().is_ok() is enough to know everything passed.

A Richer Example with Four Fields

A single email field shows the shape, but a real signup form has several fields with different kinds of rules. This example adds a name with a length rule, an age with a range rule, and an optional nickname that must be present.

src/main.rs
use validator::Validate;

#[derive(Debug, Validate)]
struct Signup {
    #[validate(email)]
    email: String,
    #[validate(length(min = 3, max = 30))]
    name: String,
    #[validate(range(min = 18, max = 120))]
    age: u32,
    #[validate(required)]
    nickname: Option<String>,
}

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

    let all_bad = Signup {
        email: "nope".to_string(),
        name: "Al".to_string(),
        age: 200,
        nickname: None,
    };
    println!("all bad: {:?}", all_bad.validate());
}

Running this prints an Ok(()) for the good value and one Err for the bad value that holds four entries, one per field.

good: Ok(())
all bad: Err(ValidationErrors({"email": Field([ValidationError { code: "email", message: None, params: {"value": String("nope")} }]), "age": Field([ValidationError { code: "range", message: None, params: {"value": Number(200), "max": Number(120), "min": Number(18)} }]), "nickname": Field([ValidationError { code: "required", message: None, params: {"value": Null} }]), "name": Field([ValidationError { code: "length", message: None, params: {"max": Number(30), "value": String("Al"), "min": Number(3)} }])}))

Each entry carries a code naming the rule that failed: email, range, required, length. Each entry also carries params, a small map with the details of the check. The range entry shows the value 200 next to min 18 and max 120, so a reader can see exactly why it failed without running anything. The message field is None here because no custom message was written. Custom messages are the subject of the attributes page, where each rule learns to carry its own human-readable text.

The order of the entries inside the Err is not guaranteed. The map is a hash map, and hash maps do not keep insertion order. The output above lists email, age, nickname, name, but a different run or a different Rust version may list them in another order. Code that reads this map must look fields up by name, never by position.

Do Not Depend on Error Order:

The ValidationErrors map does not promise any order. If your code takes "the first error" by iterating the map, it may pick a different field on different runs. Always look up errors by field name when you need a specific one.

Adding the Crate to a Project You Already Have

Most readers meet validator inside an existing Axum project rather than a fresh one. The steps are the same, but the file already has dependencies in it, so the new line goes inside the existing [dependencies] section.

1

Step 1: Open Cargo.toml

Open the Cargo.toml at the root of your project and find the [dependencies] section. It already holds lines for axum, tokio, and serde.

2

Step 2: Add the validator line

Add validator = { version = "0.21", features = ["derive"] } inside that section, on its own line. Keep the lines in alphabetical order if the file already is, so the next reader finds it fast.

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

Step 3: Build once

Run cargo build in a terminal. Cargo downloads the crate and its own dependencies, then compiles them. The first build takes a while because it compiles the new crates from scratch. Later builds reuse the compiled result.

cargo build
4

Step 4: Confirm the version in Cargo.lock

Open Cargo.lock and search for validator. The lock file records the exact version Cargo picked, such as 0.21.0. That file is what makes every other machine build with the same versions you used.

An alternative to editing the file by hand is the cargo add command, which edits Cargo.toml for you.

cargo add validator --features derive

That command writes the same line into [dependencies] and updates Cargo.lock in one step. It needs network access to crates.io the first time, just like a build does. Either route ends in the same file, so pick the one you find easier to read.

Checking Which Version You Got

The version in Cargo.toml says 0.21, but the exact release Cargo picked lives in Cargo.lock. After a build, the lock file holds an entry like this.

[[package]]
name = "validator"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"

The version = "0.21.0" line is the exact release in use. If a teammate clones the project, Cargo reads this lock file and installs 0.21.0, not some other 0.21 release. That matters because the attribute names and the error shapes on the following pages were checked against 0.21.0, and a different release could in principle spell something differently.

You can also ask Cargo to show the tree of dependencies with cargo tree -p validator, which prints the crate and the crates it depends on. That output is useful when a build pulls in something unexpected, but it is not needed for normal use.

Using the Crate Without the Derive Macro

The validator crate can also be used without the derive macro. It exposes the same checks as plain functions, such as a function that tests whether a string is an email address, and the Validate trait can be implemented by hand for a type. That route exists for types where a derive macro cannot reach, but it is not the normal route for Axum handlers. The normal route is the derive macro, because it keeps the rules on the struct and generates the checking code. The pages that follow use the derive macro throughout, and the hand-written route is not needed to follow them.

What Happens When a Request Arrives

It helps to see where validator sits in the life of a request, even though this page has no server yet. The flow is short.

Client sends JSON
        |
        v
Axum reads the body and serde builds the struct
        |
        v
validate() runs every rule on the struct
        |
        v
All rules pass -> handler runs with the struct
        |
        v
Some rule fails -> 422 response with field errors

Serde runs first because validation needs a struct to check, and a struct only exists after the JSON has been parsed. Validation runs second because the handler should never see data that breaks the rules. The handler is the last step, and it only runs when the data is good. That order is the whole point of the next few pages: each one fills in one step of this flow.

Testing It

A unit test for validation needs no server and no network. It builds a struct, calls validate(), and asserts on the result. Put the test in the same file as the struct, inside a #[cfg(test)] module, which is Rust's way of marking code that only compiles when tests run.

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 good_signup_passes() {
        let signup = Signup {
            email: "ada@example.com".to_string(),
            name: "Ada".to_string(),
        };
        assert!(signup.validate().is_ok());
    }

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

    #[test]
    fn short_name_fails() {
        let signup = Signup {
            email: "ada@example.com".to_string(),
            name: "Al".to_string(),
        };
        let errors = signup.validate().unwrap_err();
        assert!(errors.field_errors().contains_key("name"));
    }
}

The first test asserts the good value passes. The other two assert that a bad value fails and that the failure is attached to the expected field name. The field_errors() method is the way to read the map of field errors out of a ValidationErrors value. It returns a map from field name to the list of errors for that field, and contains_key checks whether a field is in it. Running cargo test runs all three tests.

cargo test

The output ends with test result: ok. 3 passed; 0 failed. These tests run in milliseconds because they only build structs in memory. They are the fastest way to check a new rule: write the rule, write a value that should fail it, and run the tests.

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

Adding the Crate Without the Derive Feature

# Wrong - the derive macro stays switched off
validator = "0.21"

With this line, use validator::Validate; still works, because the trait exists either way. But #[derive(Validate)] fails to compile with this error.

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

The compiler is saying that the name Validate is known as a trait, but no derive macro by that name is available. The fix is the features = ["derive"] entry on the dependency line. This mistake is easy to make because the error message talks about the derive macro, not about the missing feature.

Derive Needs the Feature:

The #[derive(Validate)] macro only exists when the derive feature is switched on. If you see "cannot find derive macro Validate in this scope", check the validator line in Cargo.toml first, before changing any Rust code.

Expecting Validation to Run by Itself

// Wrong - nothing checks the struct here
async fn create_signup(Json(input): Json<Signup>) -> Json<Signup> {
    Json(input)
}

Adding #[derive(Validate)] to a struct does not make Axum call validate() for you. The derive macro only writes the checking code. Somebody still has to call it, and that somebody is your handler or a custom extractor. A request with a bad email reaches this handler and is returned untouched, because no code ever asked whether the data was valid. The call itself is the subject of a later page in this group.

Putting a Rule on a Type It Cannot Check

// Wrong - length checks characters, not numbers
#[derive(Debug, Validate)]
struct Signup {
    #[validate(length(min = 3))]
    age: u32,
}

The length rule only works on strings and lists, because only those have a length in characters or items. A number has a size in value, not in length, so the compiler rejects this with a type error. The rule for numbers is range, which checks whether the value sits between a minimum and a maximum. Matching the rule to the type is the first thing to check when a derive macro reports a type error.

Final Complete Example

Here is everything from this page put together: the dependencies, a struct with four rules, and a main that shows a passing value and a failing value.

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,
    #[validate(range(min = 18, max = 120))]
    age: u32,
    #[validate(required)]
    nickname: Option<String>,
}

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

    let all_bad = Signup {
        email: "nope".to_string(),
        name: "Al".to_string(),
        age: 200,
        nickname: None,
    };
    println!("all bad: {:?}", all_bad.validate());
}

Run it with cargo run. The good value prints Ok(()). The bad value prints one Err holding four field errors, one for each broken rule.

Summary

The validator crate moves the question "is this data acceptable" out of scattered if statements and into notes written on the struct itself, and that move changes who is responsible for remembering the rules. The struct carries them, the derive macro turns them into code, and one call to validate() runs them all and returns every failure at once. The single most important insight is that validation becomes a property of the data type rather than a step in a handler: anywhere the struct goes, its rules go with it, and any code that holds the struct can ask whether it is valid with the same one-line call.

That property is what the rest of this group builds on. The rules themselves are written with attributes, each rule has its own spelling and its own arguments, and the call that runs them has to be placed where bad data can still be turned away. The crate is installed and the first rule already runs, so the work ahead is learning to write the rules well and to put the call in the right place.