Field presence checks
Learn how to check by hand that required fields are present and not empty in Axum, using Option fields, trim and is_empty, and returning a validation error when a field is missing.
A field presence check is a small test your handler runs on the data a client sent, to confirm that a required field actually arrived and holds something useful. A signup form needs a name. A comment form needs text. If the name never arrives, or arrives as an empty string, the handler should stop and answer with a validation error instead of saving a record that has no name.
Where This Fits
The page before this one settled the shape of every error body in the project, so a client always reads the same JSON shape no matter which route fails. This page puts that shape to work on the first real validation job: deciding whether a required field is present. Think of it like a reception desk checking that a visitor filled in the name line on a form before handing the form to anyone else.
The Smallest Working Version
Start with one route that creates a user, and one rule: the name must be present. Create a project with these files.
# Cargo.toml
[package]
name = "validation-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
// src/errors.rs
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
Unauthorized,
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)
}
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()),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
The error type above is the shared one used across the whole project. A ValidationError carries a plain message string, and its response is status 422 with a JSON body shaped like {"error": "name is required"}. The field-by-field form of this error comes in the next topic of this group.
// src/lib.rs
use axum::{extract::Json, http::StatusCode, routing::post, Router};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Deserialize)]
pub struct CreateUserInput {
pub name: Option<String>,
}
#[derive(Serialize)]
pub struct User {
pub name: String,
}
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 async fn create_user(
Json(input): Json<CreateUserInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
let name = require_text(&input.name, "name")?;
Ok((StatusCode::CREATED, Json(User { name })))
}
pub fn app() -> Router {
Router::new().route("/users", post(create_user))
}
// src/main.rs
use validation_demo::app;
#[tokio::main]
async fn main() {
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 with cargo run, then send a request with no name field:
curl -X POST http://127.0.0.1:3000/users -H "content-type: application/json" -d '{}'
The server answers with status 422 and this body:
{"error": "name is required"}
Send a name that has real text in it:
curl -X POST http://127.0.0.1:3000/users -H "content-type: application/json" -d '{"name": "Ada"}'
The server answers with status 201 and this body:
{"name": "Ada"}
Status 201 means a new resource was created. The handler only reaches the success line when the name check passes, so a 201 here is proof the check ran and the value was good.
The Smallest Version Works:
If a request with no name returns 422 with {"error": "name is required"} and a request with a real name returns 201, the presence check is wired up correctly. Everything later on this page grows out of this one check.
How the Presence Check Works, Piece by Piece
The check lives in one small function, require_text, and the handler calls it before doing anything else. Each part of that function answers one question about the field.
The field is an Option
pub name: Option<String>,
Option is a Rust type that means "this value may or may not be there". An Option<String> holds either Some("Ada"), which means a string arrived, or None, which means nothing arrived. Declaring the field as Option<String> is what makes a hand 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 422 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 the code on this page can make it.
The match splits the three cases
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()),
}
A match is Rust's way of saying "look at this value and pick the branch that fits it". The first arm catches None, the field that never arrived, and returns a validation error naming the field. The second arm catches a Some value whose trimmed text is empty, and returns a different error. The third arm is the success path: a Some value with real text in it, trimmed and returned as a fresh String.
The if after Some(text) in the second arm is called a match guard. It is an extra condition on that arm. Without the guard, the second arm would catch every Some value, good ones included, and no name would ever pass. With the guard, only the empty ones fall into that arm, and the good ones drop through to the third arm.
The ? at the end of the call in the handler, require_text(&input.name, "name")?, is the part that turns a returned error into an early exit. When require_text returns an Err, the ? operator stops the handler at once and hands that error back to Axum, which turns it into the 422 response. When it returns Ok, the ? unwraps the string and the handler carries on. One character does the whole job of "stop on the first failure".
trim and is_empty do the empty test
trim is a method on strings that returns the same text with leading and trailing whitespace removed. Whitespace means spaces, tabs, and newlines, the blank characters that carry no visible text. is_empty returns true when a string has zero characters left. Chained together, text.trim().is_empty() is true only when the text was empty to start with or was made of whitespace alone. A name of " " (three spaces) trims down to "", which is empty, so the check catches it. A name of " Ada " trims down to "Ada", which is not empty, so it passes, and the handler stores the trimmed form.
trim Returns a Borrowed View:
trim does not change the original string. It returns a &str, a borrowed view into the original text with the blank edges cut off. The third arm calls .to_string() on that view to build a fresh owned String that the handler can keep. That is why the stored name has no leading or trailing spaces.
Three Ways a Field Can Be Missing
A client can fail to supply a field in three different ways, and a presence check has to catch all three. They look similar from the outside, but they arrive as different values inside the handler.
| What the client sent | What the handler sees | What the check answers |
|---|---|---|
No name key at all | None | 422, name is required |
"name": "" | Some("") | 422, name must not be empty |
"name": " " | Some(" ") | 422, name must not be empty |
"name": "Ada" | Some("Ada") | 201, user created |
The first row is the field that never arrived. The second row is the field that arrived with nothing in it. The third row is the sneakiest one: the field arrived, and it is not technically empty, but it holds only spaces. A check that only tested text.is_empty() would let the third row through and save a user named three spaces. A check that only tested value.is_none() would let the second and third rows through as well. The trim plus is_empty pair is what closes all three gaps in one test.
Beginners should think of the three rows as three doors a bad value can walk through. The None arm locks the first door. The trim().is_empty() guard locks the other two.
The Concept Behind a Presence Check
A presence check is the server asking one question about each required field: did the client actually give me something I can use. The server cannot trust the shape of incoming data just because it arrived as JSON. JSON only guarantees the text parses. It does not guarantee the text means anything. A missing key, an empty string, and a spaces-only string are all valid JSON, and all three are useless as a name.
Manual validation means writing these tests in plain Rust code inside the handler, with no extra crate doing the work. The handler reads the input struct field by field, tests each one with ordinary string methods, and returns an error the moment a test fails. Nothing about this is specific to Axum. The Axum part is only the wrapper: the Json extractor turns the request body into the struct, and AppError turns the returned error into the 422 response. The checking itself is plain Rust.
Why Check by Hand Instead of Letting the Extractor Reject It
A plain String field already rejects a missing key, so a beginner can fairly ask why this page bothers with Option and a hand-written check. The answer is control over three things: the message, the empty case, and the decision about what counts as present.
The extractor's rejection message is fixed by Axum. It says the field is missing, in Axum's words, and the handler cannot change it. A hand check names the field in the project's own words, and every field gets the same message pattern, which keeps the error body consistent for clients.
The extractor cannot catch an empty string at all. "name": "" is a perfectly good String as far as deserialization is concerned, so it sails through and reaches the handler. Only a hand check can look inside the string and decide that empty is not good enough.
The extractor also cannot make judgement calls. A bio field that is absent should be fine, while a name field that is absent should fail. A field that is present but holds only spaces should fail, while a field that is present with spaces around real text should pass after trimming. These are decisions about the meaning of the data, not about its shape, and meaning is the handler's job.
Bad Types Still Belong to the Extractor:
Making a field Option<String> only changes what happens when the key is absent or holds a string. If the client sends "name": 42, the JSON extractor still rejects the request before the handler runs, because 42 is not a string.
A Richer Complete Example
Real forms have more than one field, and some fields are required while others are not. This example grows the smallest version into a signup form with a required name, a required email, and an optional bio. The same require_text helper checks both required fields, and a second helper handles the optional one.
// src/lib.rs
use axum::{extract::Json, http::StatusCode, routing::post, Router};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Deserialize)]
pub struct CreateUserInput {
pub name: Option<String>,
pub email: Option<String>,
pub bio: Option<String>,
}
#[derive(Serialize)]
pub struct User {
pub name: String,
pub email: String,
pub bio: Option<String>,
}
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 {
Some(text) if !text.trim().is_empty() => Some(text.trim().to_string()),
_ => None,
}
}
pub async fn create_user(
Json(input): Json<CreateUserInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
let name = require_text(&input.name, "name")?;
let email = require_text(&input.email, "email")?;
let bio = optional_text(&input.bio);
Ok((
StatusCode::CREATED,
Json(User { name, email, bio }),
))
}
pub fn app() -> Router {
Router::new().route("/users", post(create_user))
}
The handler now reads like a short checklist: name, then email, then bio. The ? after each require_text call means the first failing field stops the handler, so a request missing both the name and the email reports only the name. That order is the order of the calls in the handler, top to bottom, and a beginner reading the handler can see exactly which field gets reported first.
The bio uses optional_text instead of require_text, and the difference between the two helpers is the whole difference between a required field and an optional one. optional_text never returns an error. When the bio is absent, empty, or whitespace-only, it returns None, and the saved user simply has no bio. When the bio holds real text, it returns the trimmed text wrapped in Some. The same three cases that fail for a required field quietly become "no value" for an optional one.
Send a request with a name, an email, and a bio that is only spaces:
curl -X POST http://127.0.0.1:3000/users -H "content-type: application/json" -d '{"name": "Ada", "email": "ada@example.com", "bio": " "}'
The server answers with status 201 and this body:
{"name": "Ada", "email": "ada@example.com", "bio": null}
The bio came back as null because the spaces-only bio was treated as no bio at all. Send the same request with the email missing:
curl -X POST http://127.0.0.1:3000/users -H "content-type: application/json" -d '{"name": "Ada"}'
The server answers with status 422 and this body:
{"error": "email is required"}
The name passed, so the handler moved on to the email, found it missing, and stopped there.
One Helper for Every Required Text Field:
require_text takes the field name as an argument, so the same function checks the name, the email, and any other required text field added later. A new required field costs one line in the handler and one field in the input struct. Nothing else changes.
Checking an Optional Field Without Requiring It
Optional fields trip beginners up because Option appears in two different roles on this page. For a required field, Option is a trick that lets the handler see an absence and reject it. For an optional field, Option means what it says: the value may legitimately be absent, and absence is a fine answer.
The rule for an optional field is simple to state: absence is allowed, emptiness is treated as absence, and real text is kept after trimming. optional_text encodes exactly that rule. Its match has two arms. The first arm catches a Some value with non-empty trimmed text and keeps it. The second arm is _, a catch-all pattern that matches everything else, and it returns None. The catch-all is what makes the helper unable to fail: every input lands in one of the two arms, and neither arm produces an error.
A common mistake is to reuse require_text for an optional field and then wonder why requests without a bio get rejected. The two helpers exist because the two kinds of field have different rules, and using the wrong helper applies the wrong rule.
Trimming Before Saving
Trimming is not only a test. It is also a cleanup step. The success arm of require_text returns text.trim().to_string(), so the stored name never carries the spaces the client typed around it. A client that sends " Ada " gets a user named "Ada", not a user named " Ada ".
This matters more than it looks. A name stored with trailing spaces will not match the same name typed without spaces in a search box. Two users called "Ada" and "Ada " look identical on screen and behave as different people in storage. Trimming at the door, in the same function that checks presence, keeps the stored data clean without a second pass over it later.
Collecting Every Missing Field Instead of Stopping at the First
The handler above stops at the first failing field. That is the simplest behaviour, and it is often the right one. A form with five missing fields can also be more helpful if it lists all five at once, so the client can fix everything in one round instead of submitting five times. This variation collects the missing fields into a list and reports them together.
// src/lib.rs
pub fn collect_missing(input: &CreateUserInput) -> Vec<String> {
let mut missing = Vec::new();
if require_text(&input.name, "name").is_err() {
missing.push("name is required".to_string());
}
if require_text(&input.email, "email").is_err() {
missing.push("email is required".to_string());
}
missing
}
Vec is Rust's growable list type, and Vec<String> is a list of strings. The function starts with an empty list, tests each field, and pushes a message onto the list for each one that fails. It calls require_text and checks .is_err(), which is true when the result is an error and false when it is a success. The returned string from a passing check is thrown away here, because this function only cares about which fields failed.
A handler using this function checks the list before building the user:
// src/lib.rs
let missing = collect_missing(&input);
if !missing.is_empty() {
return Err(AppError::ValidationError(missing.join("; ")));
}
join("; ") glues the list of messages into one string with "; " between each pair, so two missing fields produce "name is required; email is required". The error is still a single ValidationError with a single message, so the response body keeps the plain shape from the start of this page. Fail-fast is simpler to write and simpler to reason about. Collect-all costs a little more code and gives the client the full list in one response.
How a Request Flows Through the Check
Client sends JSON body
|
v
Json extractor turns the body into CreateUserInput
|
v
Handler calls require_text for the name
|
v
Name missing or blank ----> AppError::ValidationError
| |
| v
| 422 {"error": "name is required"}
|
v
Handler calls require_text for the email
|
v
Email missing or blank --> AppError::ValidationError
| |
| v
| 422 {"error": "email is required"}
|
v
Handler builds the User and returns 201
The diagram shows why the order of the calls matters. The name is tested before the email, so a request missing both reports the name. Each test is a gate, and the request only reaches the success line after passing every gate.
Testing It
Tests for a presence check send requests straight to the router without starting a server. The tower crate provides oneshot, a method that runs one request through the router and returns the response. Add it as a dev-dependency, which is a dependency used only by tests:
# Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
// tests/user_test.rs
use axum::{
body::Body,
http::{Request, StatusCode},
};
use tower::ServiceExt;
use validation_demo::app;
async fn post_user(body: &str) -> (StatusCode, String) {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/users")
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
(status, String::from_utf8(bytes.to_vec()).unwrap())
}
#[tokio::test]
async fn missing_name_returns_422() {
let (status, body) = post_user(r#"{"email": "ada@example.com"}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body, r#"{"error":"name is required"}"#);
}
#[tokio::test]
async fn empty_name_returns_422() {
let (status, body) = post_user(r#"{"name": "", "email": "ada@example.com"}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body, r#"{"error":"name must not be empty"}"#);
}
#[tokio::test]
async fn whitespace_only_name_returns_422() {
let (status, body) = post_user(r#"{"name": " ", "email": "ada@example.com"}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body, r#"{"error":"name must not be empty"}"#);
}
#[tokio::test]
async fn valid_user_returns_201_with_trimmed_name() {
let (status, body) = post_user(r#"{"name": " Ada ", "email": "ada@example.com"}"#).await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(
body,
r#"{"name":"Ada","email":"ada@example.com","bio":null}"#
);
}
Each test covers one of the three missing cases plus the success case, and the success test also checks that the stored name was trimmed. Run them with cargo test. All four pass against the code on this page, including the whitespace-only case, which is the one most likely to slip through an incomplete check.
What the Tests Prove:
Four tests, four behaviours: absent, empty, whitespace-only, and valid. If all four pass, the handler catches every way a field can be missing and still accepts a good value. A new required field only needs one more test in the same shape.
Common Beginner Mistakes
Declaring a required field as a plain String
// Wrong - the handler never sees a missing field
#[derive(Deserialize)]
pub struct CreateUserInput {
pub name: String,
}
With a plain String, a request that omits the name never reaches create_user. The JSON extractor rejects it first with Axum's own message, and the hand check never runs. The code compiles, the server runs, and the behaviour looks almost right, which is why this mistake survives so long. The fix is the Option<String> from the smallest example: it lets the request through the extractor so the handler can make the decision.
A Plain String Hides the Empty Case Too:
A plain String field also lets "name": "" straight through to the handler, because an empty string is a valid string. Only the hand check with trim and is_empty catches it. If a field must hold real text, it needs the check no matter how it is declared.
Testing only for an empty string
// Wrong - a name of three spaces passes this test
if input.name.as_deref() == Some("") {
return Err(AppError::ValidationError("name must not be empty".to_string()));
}
This test compares the value against "" and nothing else. A name of " " is not equal to "", so it passes, and a user named three spaces gets saved. The fix is the pair from this page: text.trim().is_empty(). Trim first, then test for empty, and the whitespace-only case collapses into the empty case.
Checking presence after saving
// Wrong - the bad record is already stored when the check runs
save_user(&input);
let name = require_text(&input.name, "name")?;
Validation must run before any side effect. Saving first and checking second means a failed check leaves a bad record behind, and the client gets an error for a user that already exists in storage. The handler on this page checks first, saves second, and returns the error before anything is stored. When a handler grows a database call or a file write, the checks stay at the top, above all of it.
Returning 400 for a failed presence check
// Wrong - 400 means the request could not be read at all
(StatusCode::BAD_REQUEST, "name is required")
Status 400 means the request itself was malformed: broken JSON, a wrong content type, a body the server could not parse. A request with 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. 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.
Forgetting to trim before storing
// Wrong - the stored name keeps the surrounding spaces
Some(text) => Ok(text.clone()),
This arm passes the check but stores the raw text, spaces included. The check used the trimmed text and the stored value used the untrimmed one, so the two disagree. The fix is the arm from this page: return text.trim().to_string(), so the value that passed the test is the value that gets stored.
Final Complete Example
Here is everything from the page put together: the shared error type, the input struct with two required fields and one optional field, the two helpers, the handler, the server entry point, and the tests.
// src/errors.rs
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
Unauthorized,
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)
}
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()),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
// src/lib.rs
use axum::{extract::Json, http::StatusCode, routing::post, Router};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Deserialize)]
pub struct CreateUserInput {
pub name: Option<String>,
pub email: Option<String>,
pub bio: Option<String>,
}
#[derive(Serialize)]
pub struct User {
pub name: String,
pub email: String,
pub bio: Option<String>,
}
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 {
Some(text) if !text.trim().is_empty() => Some(text.trim().to_string()),
_ => None,
}
}
pub async fn create_user(
Json(input): Json<CreateUserInput>,
) -> Result<(StatusCode, Json<User>), AppError> {
let name = require_text(&input.name, "name")?;
let email = require_text(&input.email, "email")?;
let bio = optional_text(&input.bio);
Ok((
StatusCode::CREATED,
Json(User { name, email, bio }),
))
}
pub fn app() -> Router {
Router::new().route("/users", post(create_user))
}
// src/main.rs
use validation_demo::app;
#[tokio::main]
async fn main() {
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();
}
# Cargo.toml
[package]
name = "validation-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the checks with:
cargo test
Run the server with:
cargo run
Try the three failing requests from the testing section and the valid one, and compare the responses with the ones shown there. The behaviour of the final example is the behaviour of the smallest example grown up: same check, same error shape, more fields.
Summary
A presence check is a gate, and the gate has three locks: the field must arrive, it must not be empty, and it must not be only whitespace. Option makes the first lock possible by letting the handler see an absence. trim plus is_empty makes the other two locks possible by testing the text after its blank edges are cut away. The same helper serves every required text field, and its twin serves optional fields by turning absence into None instead of an error.
The decision that carries forward from this page is where validation lives. It lives in the handler, in plain Rust, before anything is saved, and it returns the project's own error type so the response keeps the project's own shape. That placement is what the rest of manual validation builds on: the next checks do not need a new mechanism, only new tests inside the same functions.