Calling validate in handlers
Learn how to call validate inside an Axum handler, read the field names and messages out of ValidationErrors, and return the 422 field-error response
Calling validate() inside a handler is the moment validation stops being a property of a struct and starts being a decision in a request. The handler receives the parsed input, calls validate() on it, and either goes on with good data or answers with a 422 response that lists every bad field. Nothing about the call is automatic. The handler has to write it.
Where This Fits
The validate field attributes page wrote the rules and their messages on the struct. The rules exist, the messages exist, and validate() can already report every failure. What does not exist yet is the call: nobody runs the check when a request arrives. This page adds that call, in the one place where bad data can still be turned away before the handler uses it.
Think of the struct as a form with its rules printed on it, and the handler as the clerk who receives the form. The printed rules do nothing on their own. The clerk has to read the form against the rules and either file it or hand it back with the problems marked. The handler is that clerk.
The Smallest Working Version
The smallest version is a handler that takes JSON, validates it, and answers with the field-error body when validation fails. It needs three files: the error module, the library with the route, and the entry point.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;
use validator::ValidationErrors;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
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.clone())
}
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
};
let body = json!({ "error": message });
(status, Json(body)).into_response()
}
}
pub fn validation_failed(errors: &ValidationErrors) -> Response {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for (field, kind) in errors.field_errors() {
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
fields.insert(field.to_string(), messages);
}
let body = json!({
"error": "validation failed",
"fields": fields,
});
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
use axum::{Json, Router, routing::post};
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::errors::validation_failed;
pub mod errors;
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Signup {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
pub name: String,
#[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
pub age: u32,
}
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
Ok(Json(input))
}
pub fn app() -> Router {
Router::new().route("/signup", post(create_signup))
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
[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"
thiserror = "2.0"
Start the server with cargo run, then send a bad signup in a second terminal.
curl -X POST http://127.0.0.1:3000/signup -H "content-type: application/json" -d '{"email":"not-an-email","name":"Al","age":12}'
The response has status 422 and this body, exactly as the server returns it.
{"error":"validation failed","fields":{"age":["age must be between 18 and 120"],"email":["enter a valid email address"],"name":["name must be between 3 and 30 characters"]}}
Send a good signup and the same route answers 200 with the data echoed back.
curl -X POST http://127.0.0.1:3000/signup -H "content-type: application/json" -d '{"email":"ada@example.com","name":"Ada","age":30}'
{"email":"ada@example.com","name":"Ada","age":30}
Both responses were produced by running this code against validator 0.21.0 and axum 0.8.9. The field order inside fields may vary between runs, because the map behind it does not keep order, but the shape is always the same: an error string and a fields map from field name to a list of messages.
Working Setup:
If the bad request returns status 422 with a fields map and the good request returns status 200 with the echoed JSON, the handler is validating before it uses the data. The 422 body is the contract this page builds: {"error": "validation failed", "fields": {"field_name": ["message"]}}.
The Shape of ValidationErrors
The validate() method returns Result<(), ValidationErrors>, and the Err side is the value the handler has to read. Its definition, taken from the validator crate docs for version 0.21, is a map.
pub struct ValidationErrors(pub HashMap<Cow<'static, str>, ValidationErrorsKind>);
A HashMap is a map from keys to values. Here the key is the field name, such as "email", and the value is a ValidationErrorsKind, which says what kind of failure the field has. The kind is an enum with three variants.
pub enum ValidationErrorsKind {
Struct(Box<ValidationErrors>),
List(BTreeMap<usize, Box<ValidationErrors>>),
Field(Vec<ValidationError>),
}
The Field variant is the one this page deals with. It holds a list of ValidationError values, one per failed rule on that field. A field that fails two rules holds two entries in that list, which is why the response body gives each field a list of messages rather than a single string.
The Struct variant appears when a field holds a nested struct that failed its own validation. The List variant appears when a field holds a list of structs and one of the items failed. Both are outside the flat structs this group uses, and the helper on this page only reads the Field variant. That limit is worth knowing, because it is a real one: the helper silently leaves nested errors out of the response.
Each ValidationError inside the list has three public fields.
pub struct ValidationError {
pub code: Cow<'static, str>,
pub message: Option<Cow<'static, str>>,
pub params: HashMap<Cow<'static, str>, Value>,
}
The code is a short stable name for the rule that failed, such as "email" or "range". The message is the custom text from the attribute, present when the attribute wrote one and None when it did not. The params map holds the details of the check, such as the value that failed and the min and max limits. The handler reads code and message and ignores params, because the response body has no place for the raw limits.
Reading the Map with field_errors
The ValidationErrors type offers two ways to read its contents. The errors() method returns the whole map, including the Struct and List kinds. The field_errors() method returns only the field-level failures, as a map from field name to the list of errors for that field. The helper uses field_errors() because the response body only has room for flat field errors.
for (field, kind) in errors.field_errors() {
That one line does three things. It asks the error value for its field errors. It walks through each field name and its list of errors. And it hands the handler one field at a time, so the handler can build one entry of the response map per field. The variable field is the name, such as "email", and kind is the list of ValidationError values for that field.
Inside the loop, each error is turned into one message string.
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
The message field is an Option, so it is either Some with text or None without it. When it is Some, the text is used as it stands. When it is None, the code is used instead, so the response always has something to show. The unwrap_or_else call is the fallback: it runs only when the message is missing, and it turns the code into a string. A field with no custom messages therefore answers with codes such as "email" and "length", which are terse but still name the problem.
The loop inserts each field's messages into a fresh HashMap<String, Vec<String>>, keyed by the field name. That map is exactly the fields object in the response body. The helper then wraps it with the fixed error string and returns the whole thing as a 422 response.
field_errors Only Sees Flat Fields:
The field_errors() method returns only failures of the Field kind. A nested struct failure lives under the Struct kind and does not appear in its result. For the flat signup structs in this group that is the whole story. A struct with nested validated structs would need a helper that walks the Struct kind too.
The Handler, Line by Line
The handler is short, and every line earns its place. The signature says what the handler takes and what it can return.
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
The Json(input) extractor reads the request body and builds a Signup from it. If the JSON is malformed or a field has the wrong type, Axum rejects the request before the handler runs, and the handler never sees it. That rejection is a different path from validation: deserialization answers whether the JSON matches the shape, and validation answers whether the values are acceptable. The handler only runs when deserialization already passed.
The return type is Result<Json<Signup>, axum::response::Response>. The Ok side holds the response for good data. The Err side holds a full response, already built, for bad data. Axum accepts a Result whose error type implements IntoResponse, and Response itself does, so returning the error response directly is allowed.
The body of the handler is one decision.
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
Ok(Json(input))
The if let pattern runs validate() and matches only the failure arm. When validation fails, the handler builds the 422 response from the errors and returns early. The return is what keeps bad data out of the rest of the handler: nothing below that line ever runs for an invalid signup. When validation passes, the if let does nothing, and the handler returns the input as JSON. The input value is still owned by the handler after the check, because validate() only borrows it.
The order of the two steps matters. Validation runs before any use of the data, before any database write, and before any other handler logic. A check placed after the data is used is not a guard. It is a report written after the damage is done.
Why the Handler Returns a Response Instead of AppError
A reader who knows the AppError enum may wonder why the handler does not return Err(AppError::ValidationError(...)) instead. The reason is the shape of the body. The AppError::ValidationError variant carries one string, and its IntoResponse implementation builds the plain body {"error": "<message>"} with status 422. That shape has no room for a map of fields. The field-error body needs both an error string and a fields map, so it cannot be built from a single string without hiding the map inside that string.
Hiding the map inside the string is a real mistake, and it is worth seeing once, because the output looks almost right at first glance.
// Wrong - the fields map is smuggled inside one string
async fn create_signup(Json(input): Json<Signup>) -> Result<Json<Signup>, AppError> {
input.validate().map_err(|errors| {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for (field, kind) in errors.field_errors() {
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
fields.insert(field.to_string(), messages);
}
AppError::ValidationError(serde_json::to_string(&fields).unwrap())
})?;
Ok(Json(input))
}
Running this version against the same bad signup returns status 422, but the body is wrong.
{"error":"{\"email\":[\"enter a valid email address\"],\"age\":[\"age must be between 18 and 120\"],\"name\":[\"name must be between 3 and 30 characters\"]}"}
The error value is a JSON string that itself holds JSON text, with escaped quotes throughout. A client reading this body gets one string instead of a map, and it has to parse that string a second time to find the fields. The shape breaks the contract. The fix is the helper: build the body as a real JSON object with a fields key, and return it as a Response directly. The AppError::ValidationError variant stays in the enum for single-message validation failures elsewhere, but the field-error body is built by validation_failed, not by stuffing a map into a string.
Do Not Stringify the Fields Map:
Turning the fields map into a string and putting it inside AppError::ValidationError produces a body where error holds escaped JSON text instead of a map. Clients have to parse twice, and the shape no longer matches the contract. Build the body as a JSON object with a real fields key.
The Order of Checks in a Real Handler
A handler that does more than echo its input has to decide where validation sits among its other steps. The rule is simple: validate first, before anything that acts on the data.
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
// Only good data reaches this line.
// A database write or any other use of `input` goes here.
Ok(Json(input))
}
The comment marks the boundary. Everything above it guards. Everything below it trusts. A database insert placed above the check would store a bad signup and then report the failure, which is the worst of both worlds: the client is told the data was rejected, and the data is in the database anyway. A check placed first makes the rest of the handler simple, because the rest of the handler never has to ask whether the data is valid.
Validation also runs before any call that spends money or time, such as sending a confirmation email or calling another service. Those calls should only happen for data that passed. The one-line check at the top of the handler is what guarantees that.
Checking More Than One Thing in the Same Handler
A handler sometimes needs to check something that no attribute can express, such as whether an email address is already registered. That check belongs after validation, not before it, and it uses the plain error body rather than the field-error body.
use axum::response::IntoResponse;
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
if input.email == "taken@example.com" {
let body = serde_json::json!({ "error": "email is already registered" });
return Err((axum::http::StatusCode::CONFLICT, axum::Json(body)).into_response());
}
Ok(Json(input))
}
The shape of the handler is now two guards in a row. The first guard checks the rules on the struct and answers with the field-error body. The second guard checks a fact about the wider system and answers with the plain body and status 409, which means the request conflicts with the current state. The two guards answer different questions, so they use different bodies. Keeping them separate also keeps the client able to tell a fixable input problem from a conflict it cannot fix by editing the form.
The example uses a hard-coded address instead of a real database lookup, because the point is the shape of the handler rather than the lookup itself. A real lookup would replace the comparison with a query, and the guard around it would stay exactly the same.
What the Client Sees
The 422 status code is part of the answer. It tells the client that the server understood the request but the data in it is not acceptable. It is different from 400, which means the request itself was malformed, and different from 401 and 403, which are about who the client is. A 422 says the shape was fine and the values were not.
The body is designed so a form can use it directly. Each key in fields is a field name, and each value is a list of messages for that field. A form can take the messages for email and show them under the email box, take the messages for name and show them under the name box, and so on. The error string at the top is a short summary for a place that shows one line, such as a banner above the form. A client that only reads error still learns that validation failed. A client that reads fields learns exactly what to fix.
The Request Flow, End to End
The full path of a request through this handler looks like this.
Client sends POST /signup with JSON
|
v
Json extractor builds Signup (shape errors rejected here)
|
v
Handler calls input.validate()
|
v
Fails -> validation_failed builds 422 field-error body
|
v
Passes -> handler uses the data and answers 200
Two different rejections happen at two different steps. A body that is not valid JSON, or a field with the wrong type, is rejected by the extractor before the handler runs. A body that parses fine but breaks a rule is rejected by the handler after validate() runs. Both produce a 4xx status, but only the second one carries the fields map, because only the second one went through the validator.
Testing It
These tests send real requests through the router with oneshot, the same technique the model pages use. They need the tower crate as a dev-dependency, because oneshot comes from tower::ServiceExt.
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn invalid_signup_returns_422_field_errors() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/signup")
.header("content-type", "application/json")
.body(Body::from(
r#"{"email":"not-an-email","name":"Al","age":12}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["error"], "validation failed");
assert_eq!(body["fields"]["email"][0], "enter a valid email address");
assert_eq!(
body["fields"]["name"][0],
"name must be between 3 and 30 characters"
);
assert_eq!(body["fields"]["age"][0], "age must be between 18 and 120");
}
#[tokio::test]
async fn valid_signup_returns_200() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/signup")
.header("content-type", "application/json")
.body(Body::from(
r#"{"email":"ada@example.com","name":"Ada","age":30}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["email"], "ada@example.com");
}
#[tokio::test]
async fn one_bad_field_still_returns_422() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/signup")
.header("content-type", "application/json")
.body(Body::from(
r#"{"email":"ada@example.com","name":"Ada","age":12}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["fields"]["age"][0], "age must be between 18 and 120");
assert!(body["fields"]["email"].is_null());
assert!(body["fields"]["name"].is_null());
}
The first test is the one that pins down the contract. It checks the status, the error string, and each field's message by name. The third test checks the other half of the contract: fields that passed do not appear in the fields map at all. A test that only checks the status would miss a body that returns the right code with the wrong shape. Run the tests with cargo test and expect three passes. These tests were run against the same code while checking the examples for this page, and the invalid request returned exactly the body shown above.
Common Beginner Mistakes
Validating After Using the Data
// Wrong - the data is used before it is checked
async fn create_signup(Json(input): Json<Signup>) -> Json<Signup> {
save_signup(&input);
if input.validate().is_err() {
// Too late. The signup is already saved.
}
Json(input)
}
The check has to run before the first use of the data. A validation call after a database write, an email, or any other side effect does not undo that side effect. The handler shape on this page puts the check first and returns early, so the code below the check only ever sees good data.
Forgetting the Return on the Error Arm
// Wrong - the error response is built and then thrown away
if let Err(errors) = input.validate() {
validation_failed(&errors);
}
Ok(Json(input))
The validation_failed(&errors) call builds a response, but without return Err(...) the response value is dropped and the handler goes on to return Ok. The compiler warns about the unused value, but the code still compiles, and the handler answers 200 for bad data. The fix is the early return: return Err(validation_failed(&errors));.
Returning AppError::ValidationError for Field Errors
// Wrong - one string cannot hold a fields map
Err(AppError::ValidationError(serde_json::to_string(&fields).unwrap()))
This version returns 422, which looks right in a status-only test, but the body holds the fields map as an escaped string inside error. The fix is to return the Response that validation_failed builds. The AppError::ValidationError variant is for a single human-readable message, such as a rule that lives outside the struct, not for a map of per-field messages.
Checking Only the First Error
// Wrong - one failure hides the rest
let errors = input.validate().unwrap_err();
let first = errors.field_errors().values().next();
The validator runs every rule and returns every failure, but code that takes only the first entry throws the rest away. A form that shows one problem at a time forces the user to submit, fix, submit, fix. The helper on this page loops over the whole map, so every field's messages reach the client in one response.
Validate First, Use Second:
Every use of the input, a database write, an email, a call to another service, must sit below the validation check. A check after the first use does not protect anything. Put the if let Err block at the top of the handler and return early from it.
Final Complete Example
Here is everything from this page put together: the error module with the enum and the helper, the library with the struct and the handler, and the entry point that serves the route.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use std::collections::HashMap;
use thiserror::Error;
use validator::ValidationErrors;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
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.clone())
}
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
};
let body = json!({ "error": message });
(status, Json(body)).into_response()
}
}
pub fn validation_failed(errors: &ValidationErrors) -> Response {
let mut fields: HashMap<String, Vec<String>> = HashMap::new();
for (field, kind) in errors.field_errors() {
let messages: Vec<String> = kind
.iter()
.map(|error| {
error
.message
.clone()
.map(|message| message.to_string())
.unwrap_or_else(|| error.code.to_string())
})
.collect();
fields.insert(field.to_string(), messages);
}
let body = json!({
"error": "validation failed",
"fields": fields,
});
(StatusCode::UNPROCESSABLE_ENTITY, Json(body)).into_response()
}
use axum::{Json, Router, routing::post};
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::errors::validation_failed;
pub mod errors;
#[derive(Debug, Deserialize, Serialize, Validate)]
pub struct Signup {
#[validate(email(message = "enter a valid email address"))]
pub email: String,
#[validate(length(min = 3, max = 30, message = "name must be between 3 and 30 characters"))]
pub name: String,
#[validate(range(min = 18, max = 120, message = "age must be between 18 and 120"))]
pub age: u32,
}
pub async fn create_signup(
Json(input): Json<Signup>,
) -> Result<Json<Signup>, axum::response::Response> {
if let Err(errors) = input.validate() {
return Err(validation_failed(&errors));
}
Ok(Json(input))
}
pub fn app() -> Router {
Router::new().route("/signup", post(create_signup))
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server and send the bad signup from the start of this page. The answer is 422 with the field-error body. Send the good signup and the answer is 200 with the data echoed back.
Summary
The handler is where the rules meet the request, and the shape of the handler decides what the client can do with the answer. A single validate() call at the top, an early return with a body that names every bad field, and nothing below the check that has to wonder whether the data is good: that is the whole pattern. The most important insight is that the response body is a user interface, not a log line. A 422 with a fields map lets a form point at each broken box and say what is wrong with it, while a 422 with a single string can only say that something failed somewhere. The cost of the better body is one small helper that reads the error map field by field, and the helper pays for itself every time a user fixes three fields in one round instead of three separate submissions. The remaining repetition is that every handler which takes validated input has to write the same check, and removing that repetition is what a custom extractor is for.