Validation helpers

Learn how to write small reusable validation helper functions that check one rule each and return AppError ValidationError for bad input

A validation helper is a small pure function that checks one rule about one value and answers with a Result. When the value passes, the helper returns an empty success. When the value breaks the rule, the helper returns AppError::ValidationError carrying a message that names the field, the rule, and the fix. Handlers call these helpers instead of writing the checks inline, so the same rule is written once, tested once, and reused by every handler that needs it.

Where This Fits

Pure function tests give you the technique: call a function, compare the answer. This page applies that technique to the most reused functions in the app, the ones that decide whether client input is acceptable. The behaviour the helpers produce is the one the error handling design already fixed: a validation failure becomes status 422 with a body shaped like {"error":"title must not be empty"}. The helpers build the error, and the shared response conversion turns it into that body. The helpers never touch HTTP themselves.

Think of it like a set of measuring tools on a workbench. Each tool checks one thing: a ruler checks length, a scale checks weight. A builder reaches for the tool that fits the measurement instead of guessing by eye. A validation helper is one measuring tool, and a handler reaches for the tools it needs before it builds anything.

The Smallest Working Version

Start with one helper, check_title, in its own file. It checks two rules about a book title: the title must not be empty, and it must be at most 100 characters.

src/errors.rs
#[derive(Debug, PartialEq)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}
src/validation.rs
use crate::errors::AppError;

pub fn check_title(title: &str) -> Result<(), AppError> {
    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    if title.len() > 100 {
        return Err(AppError::ValidationError(
            "title must be at most 100 characters".to_string(),
        ));
    }
    Ok(())
}

The tests for the helper live in the same file, inside a #[cfg(test)] module, and they check the happy path, the empty case, and the boundary on both sides of the limit:

src/validation.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_title_accepts_a_normal_title() {
        assert!(check_title("Dune").is_ok());
    }

    #[test]
    fn check_title_accepts_exactly_100_characters() {
        assert!(check_title(&"a".repeat(100)).is_ok());
    }

    #[test]
    fn check_title_rejects_101_characters() {
        let error = check_title(&"a".repeat(101)).unwrap_err();
        assert_eq!(
            error,
            AppError::ValidationError("title must be at most 100 characters".to_string())
        );
    }

    #[test]
    fn check_title_rejects_empty_title() {
        let error = check_title("").unwrap_err();
        assert_eq!(
            error,
            AppError::ValidationError("title must not be empty".to_string())
        );
    }
}

Run cargo test check_title and all four pass. The helper is tested without a server, without a request, and without a database. It takes a string and returns an answer, and the tests pin that answer for every input that matters.

Working Setup:

If the four tests print ok, the helper works. A validation helper that passes its tests in isolation will behave the same way when a handler calls it, because the helper cannot see the request, the handler, or anything else. The test result is the whole proof.

Understanding check_title Line by Line

The helper is short, and each line teaches a piece of the pattern every helper on this page repeats.

The return type

pub fn check_title(title: &str) -> Result<(), AppError> {

Result<(), AppError> means the function either succeeds with nothing or fails with an AppError. The () is the unit type, an empty success, and it fits a check perfectly: when the title is fine, there is nothing to return. The caller writes check_title(&input.title)? and moves on, or matches on the result in a test. The pub makes the helper usable from handlers in other files, and the file is declared in lib.rs with pub mod validation;.

The empty check

    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }

trim() strips spaces from both ends before is_empty() tests what is left, so a title of three spaces counts as empty. The return sends the error out of the function at once. Without it, the error value would be built and thrown away, and the function would fall through to the length check and then to Ok(()). The message names the field, title, and the rule, must not be empty, so a client reading it knows exactly what to fix.

The length check

    if title.len() > 100 {
        return Err(AppError::ValidationError(
            "title must be at most 100 characters".to_string(),
        ));
    }
    Ok(())

len() counts bytes, and the rule is a rough size limit, so bytes are a fair measure here. The message states the number, 100, so the client can check its own input before sending it again. The final Ok(()) is the last expression in the function, so it becomes the return value when every check above it passed.

The Concept Behind One Rule per Helper

A helper that checks one rule is easy to name, easy to test, and easy to reuse. A helper that checks five rules is a small handler in disguise, and it inherits every problem handlers have: long tests, tangled failure cases, and a name that cannot say what it does. One rule per helper keeps each function honest. check_title checks a title. check_age checks an age. check_pages checks a page count. A handler that needs three rules calls three helpers, and each call is one line.

The helpers share one error type, AppError, and that sharing is what makes them compose. A helper that returns Result<(), AppError> can be called with ? from any handler that also returns AppError, because the ? operator only works when the error types match. If every helper invented its own error type, the handler would need a conversion for each one, and the one-line call would become a match statement. The shared enum is the reason the calls stay short.

Helpers Return Errors, Handlers Return Responses:

A validation helper never builds an HTTP response. It returns an AppError, and the response conversion that turns that error into status 422 and the {"error": "..."} body lives in src/errors.rs alongside the enum. Keeping the helper free of HTTP is what keeps it testable with plain function calls. The moment a helper imports a response type, it needs a request to test it.

Why Helpers Instead of Inline Checks

A check written inline in a handler works once. The second handler that needs the same rule copies the check, and the third copies it again. Three copies of the same rule drift apart: one gets a new limit, one gets a better message, one is forgotten. A client that sends a bad title to one route gets a different message from the same title on another route, and the tests have to cover the same rule three times.

A helper written once and called from three handlers cannot drift. The rule has one home, one message, and one set of tests. A change to the limit is a one-line edit in the helper, and every handler picks it up. The handler stays short too: a create handler that calls validate_new_book(&input.title, input.pages)? reads as one sentence, while the same handler with the checks inline reads as a wall of conditions before the real work starts.

A Richer Complete Example

A realistic validation file has helpers for presence, length, range, and count, plus the two collectors that run several helpers at once. Here is the full file, with every helper the rest of this page tests.

src/validation.rs
use crate::errors::AppError;
use std::collections::HashMap;

pub fn require_text(value: &Option<String>, field: &str) -> Result<String, AppError> {
    match value {
        None => Err(AppError::ValidationError(format!("{} is required", field))),
        Some(text) if text.trim().is_empty() => Err(AppError::ValidationError(format!(
            "{} must not be empty",
            field
        ))),
        Some(text) => Ok(text.trim().to_string()),
    }
}

pub fn optional_text(value: &Option<String>) -> Option<String> {
    match value {
        None => None,
        Some(text) if text.trim().is_empty() => None,
        Some(text) => Some(text.trim().to_string()),
    }
}

pub fn check_title(title: &str) -> Result<(), AppError> {
    if title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    if title.len() > 100 {
        return Err(AppError::ValidationError(
            "title must be at most 100 characters".to_string(),
        ));
    }
    Ok(())
}

pub fn check_age(age: i32) -> Result<(), AppError> {
    if !(0..=150).contains(&age) {
        return Err(AppError::ValidationError(
            "age must be between 0 and 150".to_string(),
        ));
    }
    Ok(())
}

pub fn check_pages(pages: u32) -> Result<(), AppError> {
    if pages == 0 {
        return Err(AppError::ValidationError(
            "pages must be at least 1".to_string(),
        ));
    }
    Ok(())
}

pub fn validate_new_book(title: &str, pages: u32) -> Result<(), AppError> {
    check_title(title)?;
    check_pages(pages)?;
    Ok(())
}

pub struct CreateProfileInput {
    pub name: Option<String>,
    pub age: i32,
}

pub fn validate_profile(input: &CreateProfileInput) -> Vec<String> {
    let mut errors = Vec::new();
    if let Err(AppError::ValidationError(message)) = require_text(&input.name, "name") {
        errors.push(message);
    }
    if let Err(AppError::ValidationError(message)) = check_age(input.age) {
        errors.push(message);
    }
    errors
}

pub fn add_error(errors: &mut HashMap<String, Vec<String>>, field: &str, message: &str) {
    errors
        .entry(field.to_string())
        .or_default()
        .push(message.to_string());
}

pub struct SignupInput {
    pub username: Option<String>,
    pub age: i32,
}

pub fn validate_signup(input: &SignupInput) -> HashMap<String, Vec<String>> {
    let mut errors: HashMap<String, Vec<String>> = HashMap::new();
    match &input.username {
        None => add_error(&mut errors, "username", "username is required"),
        Some(name) if name.trim().is_empty() => {
            add_error(&mut errors, "username", "username must not be empty")
        }
        Some(_) => {}
    }
    if let Err(AppError::ValidationError(message)) = check_age(input.age) {
        add_error(&mut errors, "age", &message);
    }
    errors
}

The tests module for this file has one test per behaviour, and it pins the exact messages, because the messages are part of the API surface and a reworded message changes what clients see.

src/validation.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn require_text_returns_trimmed_value() {
        let value = Some("  Ada  ".to_string());
        assert_eq!(require_text(&value, "name").unwrap(), "Ada");
    }

    #[test]
    fn require_text_rejects_missing_value() {
        let value: Option<String> = None;
        let error = require_text(&value, "name").unwrap_err();
        assert_eq!(
            error,
            AppError::ValidationError("name is required".to_string())
        );
    }

    #[test]
    fn require_text_rejects_spaces_only_value() {
        let value = Some("   ".to_string());
        let error = require_text(&value, "name").unwrap_err();
        assert_eq!(
            error,
            AppError::ValidationError("name must not be empty".to_string())
        );
    }

    #[test]
    fn optional_text_turns_blank_into_none() {
        assert_eq!(optional_text(&None), None);
        assert_eq!(optional_text(&Some("   ".to_string())), None);
        assert_eq!(
            optional_text(&Some("  Ada  ".to_string())),
            Some("Ada".to_string())
        );
    }

    #[test]
    fn check_age_accepts_both_ends_of_the_range() {
        assert!(check_age(0).is_ok());
        assert!(check_age(150).is_ok());
    }

    #[test]
    fn check_age_rejects_negative_and_huge_ages() {
        assert_eq!(
            check_age(-1).unwrap_err(),
            AppError::ValidationError("age must be between 0 and 150".to_string())
        );
        assert_eq!(
            check_age(151).unwrap_err(),
            AppError::ValidationError("age must be between 0 and 150".to_string())
        );
    }

    #[test]
    fn check_pages_rejects_zero() {
        assert_eq!(
            check_pages(0).unwrap_err(),
            AppError::ValidationError("pages must be at least 1".to_string())
        );
    }

    #[test]
    fn validate_new_book_reports_the_first_failure_only() {
        let error = validate_new_book("", 0).unwrap_err();
        assert_eq!(
            error,
            AppError::ValidationError("title must not be empty".to_string())
        );
    }

    #[test]
    fn validate_profile_collects_every_failure() {
        let input = CreateProfileInput {
            name: None,
            age: 200,
        };
        assert_eq!(
            validate_profile(&input),
            vec![
                "name is required".to_string(),
                "age must be between 0 and 150".to_string(),
            ]
        );
    }

    #[test]
    fn validate_profile_returns_an_empty_list_for_good_input() {
        let input = CreateProfileInput {
            name: Some("Ada".to_string()),
            age: 36,
        };
        assert!(validate_profile(&input).is_empty());
    }

    #[test]
    fn validate_signup_groups_errors_by_field() {
        let input = SignupInput {
            username: None,
            age: 200,
        };
        let errors = validate_signup(&input);
        assert_eq!(
            errors.get("username").unwrap(),
            &vec!["username is required".to_string()]
        );
        assert_eq!(
            errors.get("age").unwrap(),
            &vec!["age must be between 0 and 150".to_string()]
        );
    }

    #[test]
    fn validate_signup_returns_an_empty_map_for_good_input() {
        let input = SignupInput {
            username: Some("ada".to_string()),
            age: 36,
        };
        assert!(validate_signup(&input).is_empty());
    }

    #[test]
    fn add_error_appends_a_second_message_for_the_same_field() {
        let mut errors: HashMap<String, Vec<String>> = HashMap::new();
        add_error(&mut errors, "username", "username is required");
        add_error(&mut errors, "username", "username must not be empty");
        assert_eq!(errors.get("username").unwrap().len(), 2);
    }
}

Run cargo test validation and every test in the module passes. The module tests the helpers the way a handler uses them: one helper at a time, then the collectors that combine them.

Checking That a Field Is Present

The first question about a field is whether the client sent anything at all. require_text answers it for text fields that arrive as Option<String>, where None means the field was missing and Some means a string arrived. The helper has three arms, and each one is a different answer to that question.

pub fn require_text(value: &Option<String>, field: &str) -> Result<String, AppError> {
    match value {
        None => Err(AppError::ValidationError(format!("{} is required", field))),
        Some(text) if text.trim().is_empty() => Err(AppError::ValidationError(format!(
            "{} must not be empty",
            field
        ))),
        Some(text) => Ok(text.trim().to_string()),
    }
}

Option is a Rust type that means a value may or may not be there. Declaring the field as Option<String> is what makes this check possible at all. If the field were a plain String, a missing field would never reach the handler, because the JSON extractor rejects the request first with its own message about a missing field. That automatic rejection is useful, but it gives the handler no say in the message, and it cannot tell an empty string from a good one. Option moves the decision into the handler, where this helper can make it.

The three arms cover the three shapes of input. A missing field produces "name is required". A present but blank field, an empty string or a string of spaces, produces "name must not be empty". A present field with real text produces the text, trimmed, as the success value. Returning the trimmed string matters: the handler stores the cleaned value, not the raw one with spaces still attached, so the stored name is "Ada" even when the client sent " Ada ".

The field argument is what makes one helper serve every text field. The handler passes "name" for a name and "username" for a username, and the messages come out with the right field in them. A helper that hardcoded "name" would need a copy per field, which is the duplication the helper exists to remove.

Handling Fields a Client May Leave Out

Not every field is required. A middle name or a nickname may be absent, and absence is fine. optional_text is the twin of require_text for those fields: it turns absence into None instead of an error, and it turns a blank string into None too, so a client that sends only spaces is treated the same as a client that sent nothing.

pub fn optional_text(value: &Option<String>) -> Option<String> {
    match value {
        None => None,
        Some(text) if text.trim().is_empty() => None,
        Some(text) => Some(text.trim().to_string()),
    }
}

The return type is Option<String>, not a Result, because there is no failure here. The helper either finds real text and returns it, or it returns None. A handler stores the None directly, and the stored record simply has no value for that field. The test pins all three shapes: missing, blank, and real text with surrounding spaces.

The difference between the two helpers is a decision about the field, not about the code. A required field uses require_text and fails loudly when it is missing. An optional field uses optional_text and stays quiet. Mixing them up is a real bug: an optional field checked with require_text rejects requests that should pass, and a required field checked with optional_text stores a record with no name.

Failing Fast With the Question Mark Operator

A handler that checks several rules usually wants to stop at the first failure. validate_new_book does that by calling one helper after another with ?, which returns the error from the function at once when a helper fails and continues when it succeeds.

pub fn validate_new_book(title: &str, pages: u32) -> Result<(), AppError> {
    check_title(title)?;
    check_pages(pages)?;
    Ok(())
}

The test proves the first failure wins. A book with an empty title and zero pages fails on the title, and the pages error never appears:

#[test]
fn validate_new_book_reports_the_first_failure_only() {
    let error = validate_new_book("", 0).unwrap_err();
    assert_eq!(
        error,
        AppError::ValidationError("title must not be empty".to_string())
    );
}

Fail-fast is the simplest composition, and it fits most handlers. The response carries one message, the handler code stays linear, and the client fixes one thing and resubmits. Its cost is that a client with three broken fields learns about them one at a time, over three round trips. When that cost matters, the next two sections collect the failures instead.

Collecting Every Failure Into One List

validate_profile runs every check and gathers every failure into a Vec<String>, a list of messages. It does not stop at the first failure. It calls each helper, and when a helper returns an error it pushes the message onto the list and carries on to the next check.

pub struct CreateProfileInput {
    pub name: Option<String>,
    pub age: i32,
}

pub fn validate_profile(input: &CreateProfileInput) -> Vec<String> {
    let mut errors = Vec::new();
    if let Err(AppError::ValidationError(message)) = require_text(&input.name, "name") {
        errors.push(message);
    }
    if let Err(AppError::ValidationError(message)) = check_age(input.age) {
        errors.push(message);
    }
    errors
}

The if let pattern is how the collector reads one arm of a Result without a full match. if let Err(AppError::ValidationError(message)) = require_text(...) runs the block only when the helper failed, and binds the message to a variable inside the block. When the helper succeeds, the if let does nothing, and the function moves on to the next check. An empty list at the end means every check passed.

The handler turns the list into a single error by joining the messages with "; " between them, so the response keeps the plain shape the client already knows:

src/lib.rs
async fn create_profile(Json(input): Json<CreateProfileInput>) -> Result<Json<Book>, AppError> {
    let profile = validation::CreateProfileInput {
        name: input.name,
        age: input.age,
    };
    let errors = validate_profile(&profile);
    if !errors.is_empty() {
        return Err(AppError::ValidationError(errors.join("; ")));
    }
    Ok(Json(Book {
        id: 3,
        title: "Profile created".to_string(),
    }))
}

A profile with no name and an age of 200 produces the body {"error":"name is required; age must be between 0 and 150"} with status 422. The list order is the order the checks ran in, name first and age second, because a Vec keeps its entries in insertion order. The test asserts the whole list in that order, which pins the order as part of the behaviour.

A List Is Ordered, a Map Is Not:

The flat list keeps its order, so a test can assert the exact list. The map in the next section does not keep its order, so a test must look fields up by name. Confusing the two is the most common testing mistake on this page: an assertion on map order passes on one run and fails on the next, for no reason the code can explain.

Grouping Failures by Field Name

A joined message is readable, but a client program cannot tell which part of it belongs to which field without parsing words. validate_signup gives each failure a field name of its own, using a HashMap<String, Vec<String>>, a map from field names to lists of messages.

pub fn add_error(errors: &mut HashMap<String, Vec<String>>, field: &str, message: &str) {
    errors
        .entry(field.to_string())
        .or_default()
        .push(message.to_string());
}

add_error is the small helper that makes the map easy to use. entry(field) finds the entry for a field or creates it, or_default() supplies an empty list when the field has no entry yet, and push adds the message to that list. Without it, every call site would repeat the lookup, the default, and the push. The test proves a field can hold two messages: two calls to add_error for "username" leave a list of length two under that key.

pub fn validate_signup(input: &SignupInput) -> HashMap<String, Vec<String>> {
    let mut errors: HashMap<String, Vec<String>> = HashMap::new();
    match &input.username {
        None => add_error(&mut errors, "username", "username is required"),
        Some(name) if name.trim().is_empty() => {
            add_error(&mut errors, "username", "username must not be empty")
        }
        Some(_) => {}
    }
    if let Err(AppError::ValidationError(message)) = check_age(input.age) {
        add_error(&mut errors, "age", &message);
    }
    errors
}

A field that passes never gets an entry in the map, so an empty map means the input is valid. The handler answers with a body that carries both the plain message and the map, so a client that only reads error still gets a readable message, and a client that reads fields can highlight the right form field:

src/lib.rs
async fn create_account(Json(input): Json<SignupInput>) -> Response {
    let signup = validation::SignupInput {
        username: input.username,
        age: input.age,
    };
    let errors = validate_signup(&signup);
    if !errors.is_empty() {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": "validation failed", "fields": errors })),
        )
            .into_response();
    }
    (
        StatusCode::CREATED,
        Json(json!({ "message": "account created" })),
    )
        .into_response()
}

A signup with no username and an age of 200 returns status 422 with a body like {"error":"validation failed","fields":{"age":["age must be between 0 and 150"],"username":["username is required"]}}. The order of the fields inside fields can change between runs, because a HashMap does not keep insertion order, and the test reads them by name for that reason.

Testing Boundaries, Not Just the Middle

A range check is only proven at its edges. check_age accepts 0 to 150, and the tests pin both ends and the values just outside them.

#[test]
fn check_age_accepts_both_ends_of_the_range() {
    assert!(check_age(0).is_ok());
    assert!(check_age(150).is_ok());
}

#[test]
fn check_age_rejects_negative_and_huge_ages() {
    assert_eq!(
        check_age(-1).unwrap_err(),
        AppError::ValidationError("age must be between 0 and 150".to_string())
    );
    assert_eq!(
        check_age(151).unwrap_err(),
        AppError::ValidationError("age must be between 0 and 150".to_string())
    );
}

The middle of the range tells you almost nothing. The edges tell you whether the comparison uses the right operator. A check written as age > 0 && age < 150 would fail both edge tests, and a check written as age >= 0 && age <= 150 passes them. The same rule holds for the title length: 100 passes, 101 fails, and the two tests together pin the limit exactly. When a limit changes later, these tests fail first, which is their job.

How a Bad Value Flows

The diagram below follows one bad create request from the body to the response, through the helper that catches it.

POST /books {"title":"","pages":10}
        |
        v
Json parses the body, title is ""
        |
        v
Handler calls validate_new_book, which calls check_title
        |
        v
check_title returns Err(ValidationError("title must not be empty"))
        |
        v
The ? operator returns the error from the handler
        |
        v
IntoResponse turns the variant into a response
        |
        v
422 Unprocessable Entity, {"error":"title must not be empty"}

The message is written once, in the helper, and it survives the whole trip untouched. Nothing along the way rewords it, truncates it, or wraps it in another structure. That is why the message the client sees is the message the helper wrote, and why a test that asserts the exact message is testing the real behaviour.

Testing the Helpers Through the Handler

Unit tests prove the helpers, and one wiring test proves the helpers are connected to the response. The test below sends a bad body through the router and asserts the exact status and body, using the same request building the rest of this chapter uses.

tests/validation_wiring_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

async fn body_text(response: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

#[tokio::test]
async fn empty_title_returns_422_with_message() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books")
                .method("POST")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"","pages":10}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(
        body_text(response).await,
        r#"{"error":"title must not be empty"}"#
    );
}

#[tokio::test]
async fn profile_with_two_failures_returns_both_messages() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/profiles")
                .method("POST")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"age":200}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(
        body_text(response).await,
        r#"{"error":"name is required; age must be between 0 and 150"}"#
    );
}

#[tokio::test]
async fn account_with_bad_signup_returns_field_errors() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/accounts")
                .method("POST")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"age":200}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    let body = body_text(response).await;
    let value: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(value["error"], "validation failed");
    assert_eq!(value["fields"]["username"][0], "username is required");
    assert_eq!(
        value["fields"]["age"][0],
        "age must be between 0 and 150"
    );
}

The third test parses the body as JSON and reads the fields by name, because the map order is unspecified. All three tests passed against the scratch project. Run them with cargo test and expect:

test empty_title_returns_422_with_message ... ok
test profile_with_two_failures_returns_both_messages ... ok
test account_with_bad_signup_returns_field_errors ... ok

The body_text helper reads the response body and turns it into a String, so the tests can share the reading logic instead of repeating it. The .method("POST") call sets the request method, and the content-type header tells the Json extractor the body is JSON.

Common Beginner Mistakes

Validating after writing to the store

// Wrong - the bad row is already stored when the check runs
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
    let book = store_book(&input);
    if input.title.trim().is_empty() {
        return Err(AppError::ValidationError(
            "title must not be empty".to_string(),
        ));
    }
    Ok(Json(book))
}

Validation runs before any side effect. If the check runs after the write, the bad data is already in the store when the error returns, and the client believes the create failed while the store holds a row with an empty title. Check first, write second, and never let a failed request leave a trace behind. A unit test on the helper cannot catch this, because the helper is correct either way. Only the handler test, or a careful reading of the handler, catches it.

Forgetting trim and accepting spaces as a title

// Wrong - "   " passes the check and becomes a book title
if input.title.is_empty() {
    return Err(AppError::ValidationError(
        "title must not be empty".to_string(),
    ));
}

is_empty() on " " returns false, because the string has three characters in it. The book is created with a title of spaces, which displays as nothing everywhere it appears. The fix is input.title.trim().is_empty(), which strips the spaces first and then tests what remains. The require_text tests pin this with a spaces-only input, so the mistake fails a test the moment it is made.

Returning a plain String instead of the shared error

// Wrong - a bare String is not the shared error type
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, String> {
    if input.title.trim().is_empty() {
        return Err("title must not be empty".to_string());
    }
    Ok(Json(Book { id: 2, title: input.title }))
}

This compiles, and it breaks the design. The handler now returns a different error type from every other handler, the response conversion for AppError never sees it, and the client gets a different body shape for this failure than for the others. The fix is to return AppError::ValidationError with the message inside, so the handler shares the type, the conversion, and the body shape with the rest of the app.

A String Error Bypasses the Whole Design:

Returning Result<Json<Book>, String> means Axum turns the string into a plain-text 500 response, because a String error has no status mapping of its own. A validation failure would then arrive as a server error with the wrong status and the wrong body, and the client would treat a fixable input problem as a broken server.

Using 400 for a validation failure

A missing name is perfectly readable JSON that the server understood and then judged incomplete. That is what 422 is for, and it is what AppError::ValidationError maps to. Status 400 means the request itself was malformed: broken JSON, a wrong content type, a body the server could not parse. Using 400 for a validation failure tells the client the request was unreadable, which sends the client looking for a syntax problem that does not exist. The helpers on this page never choose a status code, which is the point: the status lives in the one response conversion, and every helper inherits the right one.

Collecting errors and forgetting to check the list

// Wrong - the errors are collected and then ignored
let errors = validate_profile(&profile);
Ok(Json(Book { id: 3, title: "Profile created".to_string() }))

A collector that returns a list does not stop anything on its own. The handler must check if !errors.is_empty() and return the error before doing any work. Forgetting the check means a profile with no name and an impossible age is created anyway, and the validation code runs for nothing. The fail-fast shape with ? does not have this failure mode, because the operator returns the error by itself. When you choose collect-all, the empty check is part of the pattern, not an optional extra.

Final Complete Example

Here is everything from this page in one place: the shared error type with its response conversion, the validation file, the handlers that use it, and the wiring tests.

src/errors.rs
use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use serde_json::json;

#[derive(Debug, PartialEq)]
pub enum AppError {
    NotFound,
    ValidationError(String),
    InternalError,
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
            AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            AppError::InternalError => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "something went wrong".to_string(),
            ),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
src/lib.rs
pub mod errors;
pub mod validation;

use axum::{
    Json,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
use serde_json::json;
use validation::{validate_new_book, validate_profile, validate_signup};

#[derive(Debug, PartialEq, Serialize)]
pub struct Book {
    pub id: u32,
    pub title: String,
}

#[derive(Deserialize)]
pub struct NewBook {
    pub title: String,
    pub pages: u32,
}

#[derive(Deserialize)]
pub struct CreateProfileInput {
    pub name: Option<String>,
    pub age: i32,
}

#[derive(Deserialize)]
pub struct SignupInput {
    pub username: Option<String>,
    pub age: i32,
}

async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
    validate_new_book(&input.title, input.pages)?;
    Ok(Json(Book {
        id: 2,
        title: input.title,
    }))
}

async fn create_profile(Json(input): Json<CreateProfileInput>) -> Result<Json<Book>, AppError> {
    let profile = validation::CreateProfileInput {
        name: input.name,
        age: input.age,
    };
    let errors = validate_profile(&profile);
    if !errors.is_empty() {
        return Err(AppError::ValidationError(errors.join("; ")));
    }
    Ok(Json(Book {
        id: 3,
        title: "Profile created".to_string(),
    }))
}

async fn create_account(Json(input): Json<SignupInput>) -> Response {
    let signup = validation::SignupInput {
        username: input.username,
        age: input.age,
    };
    let errors = validate_signup(&signup);
    if !errors.is_empty() {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": "validation failed", "fields": errors })),
        )
            .into_response();
    }
    (
        StatusCode::CREATED,
        Json(json!({ "message": "account created" })),
    )
        .into_response()
}

pub fn app() -> Router {
    Router::new()
        .route("/books", post(create_book))
        .route("/profiles", post(create_profile))
        .route("/accounts", post(create_account))
}

The Cargo.toml is the same project file as the previous pages, with axum, tokio, serde, and serde_json as dependencies and tower as a dev-dependency for the wiring tests. Run cargo test and expect 32 library tests to pass with 1 ignored, plus the 3 wiring tests.

Summary

The choice a handler faces is not whether to validate, but how to report it, and the three shapes on this page are the decision framework. When the client should fix one thing and resubmit, fail fast with ? and return the first error, because one message is the clearest answer. When the client should see everything wrong at once and the response can stay a single message, collect into a list and join it, because the client gets the full picture in one round trip. When the client is a form that highlights fields, group by field name in a map, because a client program should never have to parse a sentence to find which field failed. Under all three shapes the rule is the same: one helper per rule, one message per failure, the message written where the rule broke, and the status and body shape decided once in the shared error conversion. A helper tested in isolation is a helper you can trust from every handler that calls it.