Range and length checks
Learn how to check numbers against a range and strings against a length by hand in Axum, collecting every failure and returning one validation error.
A range check asks whether a number sits between two limits. A length check asks whether a string has between two counts of characters. An age of 200 is outside the range of real human ages. A username of two characters is shorter than the shortest name a form allows. Both checks are the same idea applied to different kinds of value: the data arrived, it has the right type, and now the handler has to decide whether the value itself is acceptable.
Where This Fits
The page before this one taught the first manual check: whether a required field is present at all. That check answers "did the client send anything". This page answers the next question: "is what they sent within the limits". Think of it like a bouncer who first checks that a visitor has a ticket, and then checks that the ticket is for tonight and not for last month.
The Smallest Working Version
Start with one route, one number, and one rule: an age between 0 and 150. Create a project with these files. The error type is the shared one from the project, with ValidationError mapping to status 422 and a plain {"error": "..."} body. The field-by-field form of this error comes in the next topic of this group.
# 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()
}
}
// src/lib.rs
use axum::{extract::Json, http::StatusCode, routing::post, Router};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Deserialize)]
pub struct CreateProfileInput {
pub age: i32,
}
#[derive(Serialize)]
pub struct Profile {
pub age: i32,
}
pub async fn create_profile(
Json(input): Json<CreateProfileInput>,
) -> Result<(StatusCode, Json<Profile>), AppError> {
if !(0..=150).contains(&input.age) {
return Err(AppError::ValidationError(
"age must be between 0 and 150".to_string(),
));
}
Ok((StatusCode::CREATED, Json(Profile { age: input.age })))
}
pub fn app() -> Router {
Router::new().route("/profiles", post(create_profile))
}
// 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 an age outside the range:
curl -X POST http://127.0.0.1:3000/profiles -H "content-type: application/json" -d '{"age": 200}'
The server answers with status 422 and this body:
{"error": "age must be between 0 and 150"}
Send an age inside the range:
curl -X POST http://127.0.0.1:3000/profiles -H "content-type: application/json" -d '{"age": 36}'
The server answers with status 201 and this body:
{"age": 36}
The check is one if in the handler, and it runs before anything is built or saved. A value inside the range falls through to the success line. A value outside it returns early with the validation error.
The Smallest Version Works:
If 200 returns 422 with the age message and 36 returns 201, the range check is wired up correctly. Every other check on this page is the same shape with different limits.
How a Range Check Works, Piece by Piece
The whole check is this line:
if !(0..=150).contains(&input.age) {
Three pieces of Rust work together here, and each one is worth understanding on its own because all three appear again in the length check.
0..=150 is a range, a value that stands for every number from 0 to 150. The ..= form is called an inclusive range, because it includes both ends: 0 counts as inside, and 150 counts as inside. The other form, 0..150, is an exclusive range, and it stops one short: 149 is inside, 150 is outside. For an age limit, the inclusive form is the one that matches the words "between 0 and 150", because a person can be 150 years old in the rule as stated. Using 0..150 by mistake would reject a 150-year-old for no reason, and the error message would still say "between 0 and 150", so the client would have no way to see why.
.contains(&input.age) is a method on the range that answers true when the number sits inside it and false when it does not. It reads almost like the English sentence: "does 0 to 150 contain this age". The & before input.age means the method borrows the number instead of taking ownership of it. Numbers are cheap to copy, so the borrow here is a convention of the method's signature rather than something the reader has to manage.
The ! in front flips the answer. The if needs to run when the age is outside the range, and contains answers true when it is inside, so the ! turns "inside" into "not inside". Beginners sometimes write the test the other way round, if input.age < 0 || input.age > 150, and that works too. The range form is shorter, it states both limits in one place, and it cannot drift apart the way two separate comparisons can when one limit changes and the other is forgotten.
Why the age is an i32
The input field is declared as i32, a signed 32-bit integer, which is a whole number that can be negative. That choice is deliberate. A negative age like -5 is exactly the kind of bad value a range check should catch and report with the project's own message. If the field were u8, an unsigned 8-bit integer that cannot be negative, the JSON extractor would reject -5 before the handler ever ran, with Axum's own message about an invalid number. The handler would never get its say.
The same reasoning applies to the top end. An i32 holds numbers far above 150, so 200 and 10000 both reach the handler and both get the same clear message. A u8 holds at most 255, so 10000 would be rejected by the extractor instead. For a field the handler is meant to validate, the type should be wide enough to let bad values arrive, so the handler can be the one that judges them. Pick the type for what the check needs to see, not for the smallest box the good values fit in.
i32 Is the Ordinary Integer Choice:
i32 is Rust's default integer type for whole numbers that can be negative. A plain let age = 36; in Rust is an i32 unless the code says otherwise. Using it for the age field keeps the input struct consistent with ordinary Rust code.
The Concept Behind Range and Length Checks
A presence check asks whether a value exists. A range check and a length check ask whether an existing value is reasonable. The two questions are different, and they fail in different ways. A missing field is a client that forgot something. An age of 200 is a client that sent something impossible. The server treats the two differently because the client fixes them differently: one by supplying the field, the other by correcting the value.
Both checks share one mechanism: compare the value against limits and collect the failure as a message. The comparison is ordinary Rust. There is no special validation syntax to learn and no annotation that runs behind the handler's back. The handler reads the number, compares it, and pushes a message when the comparison fails. A length check does the same with a string: count its characters, compare the count against the limits, and push a message when the count falls outside.
Beginners should think of these checks as a ruler and a fence. The range is a fence around the numbers that make sense. The length limits are a fence around the strings that make sense. The handler measures each value against its fence and reports the ones that fall outside. The fence itself is just two numbers in the code, which is why changing a limit later is a one-line edit.
Checking a String Length
A username needs a length check, not a range check, because a string is not a number. The count that matters is the count of characters, and Rust counts them with chars().count(). This example adds a username of 3 to 30 characters to the profile from the smallest version.
// src/lib.rs
#[derive(Deserialize)]
pub struct CreateProfileInput {
pub username: String,
pub age: i32,
}
pub fn validate_profile(input: &CreateProfileInput) -> Vec<String> {
let mut errors = Vec::new();
let length = input.username.chars().count();
if length < 3 {
errors.push("username must be at least 3 characters long".to_string());
}
if length > 30 {
errors.push("username must be at most 30 characters long".to_string());
}
if !(0..=150).contains(&input.age) {
errors.push("age must be between 0 and 150".to_string());
}
errors
}
chars() turns the string into an iterator over its characters, and count() counts how many there are. Counting characters this way matters because Rust strings are UTF-8, a text encoding in which some characters take more than one byte. The letter e takes one byte. The letter e with an accent takes two bytes. A username of thirty accented characters is 30 characters long but 60 bytes long. Counting bytes with .len() would call it 60 and reject it as too long, even though a reader sees 30 characters. Counting with chars().count() measures what the reader sees.
The two length tests are separate if statements, not an if with an else. A username cannot be both too short and too long at once, so the two forms behave the same here. Separate statements keep the pattern uniform: one test, one message, one push. When a later check needs two messages for one field, the same shape extends without restructuring.
The function returns a Vec<String>, a list of error messages. It starts empty, and each failing test pushes one message onto it. A valid profile produces an empty list. That empty list is how the handler knows everything passed: it does not need a separate true or false, because "no errors collected" already means "valid".
Count Characters, Not Bytes:
.len() on a string returns the number of bytes, not the number of characters. For plain English text the two counts agree, which is why the mistake goes unnoticed until a user types an accented letter or an emoji. chars().count() is the count that matches what the user typed.
Collecting What Failed
The smallest version returned on the first failure. The validate_profile function above does something different: it runs every test, collects every failure, and hands the whole list back. The handler then decides what to do with the list.
// src/lib.rs
pub async fn create_profile(
Json(input): Json<CreateProfileInput>,
) -> Result<(StatusCode, Json<Profile>), AppError> {
let errors = validate_profile(&input);
if !errors.is_empty() {
return Err(AppError::ValidationError(errors.join("; ")));
}
Ok((
StatusCode::CREATED,
Json(Profile {
username: input.username,
age: input.age,
}),
))
}
The handler calls the validate function first, before building anything. If the list is not empty, it glues the messages into one string with join("; ") and returns a single ValidationError. A request with a two-character username and an age of 200 produces this body:
{"error": "username must be at least 3 characters long; age must be between 0 and 150"}
Both failures appear in one response, in the order the tests ran: username first, age second. The client can fix both and resubmit once, instead of fixing the username, resubmitting, and only then learning about the age.
Separating the checks into validate_profile and the response into the handler is what makes collecting possible. A function that returns on the first failure cannot collect a second one, because it has already left. A function that returns a list runs every test no matter how the earlier ones went, and the handler is the one place that turns the list into an error. The split also keeps the handler short: it calls one function, checks one list, and builds the success value.
The Order of the Messages Is the Order of the Tests:
The messages in the joined error appear in the order the if statements run in validate_profile, because each push appends to the end of the list. A client reading the message sees the username problem before the age problem because the username test comes first in the function. Keeping the tests in the same order as the fields in the input struct makes that order predictable.
A Richer Complete Example
A real profile form has a third field: an optional bio with a maximum length but no minimum. This example grows the handler to cover it, and shows how an optional field fits the collecting pattern.
// src/lib.rs
use axum::{extract::Json, http::StatusCode, routing::post, Router};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Deserialize)]
pub struct CreateProfileInput {
pub username: String,
pub age: i32,
pub bio: Option<String>,
}
#[derive(Serialize)]
pub struct Profile {
pub username: String,
pub age: i32,
pub bio: Option<String>,
}
pub fn validate_profile(input: &CreateProfileInput) -> Vec<String> {
let mut errors = Vec::new();
let length = input.username.chars().count();
if length < 3 {
errors.push("username must be at least 3 characters long".to_string());
}
if length > 30 {
errors.push("username must be at most 30 characters long".to_string());
}
if !(0..=150).contains(&input.age) {
errors.push("age must be between 0 and 150".to_string());
}
if let Some(bio) = &input.bio {
if bio.chars().count() > 200 {
errors.push("bio must be at most 200 characters long".to_string());
}
}
errors
}
pub async fn create_profile(
Json(input): Json<CreateProfileInput>,
) -> Result<(StatusCode, Json<Profile>), AppError> {
let errors = validate_profile(&input);
if !errors.is_empty() {
return Err(AppError::ValidationError(errors.join("; ")));
}
Ok((
StatusCode::CREATED,
Json(Profile {
username: input.username,
age: input.age,
bio: input.bio,
}),
))
}
pub fn app() -> Router {
Router::new().route("/profiles", post(create_profile))
}
The bio test uses if let Some(bio) = &input.bio, a pattern that runs the body only when the bio is present and skips it entirely when the bio is absent. An absent bio is not an error, so there is nothing to push. A present bio gets its character count measured against the 200 limit, and only a bio over the limit produces a message. There is no minimum length for a bio, because an empty bio is the same as no bio, and the form does not require one.
Send a request that fails all three checks at once:
curl -X POST http://127.0.0.1:3000/profiles -H "content-type: application/json" -d '{"username": "ad", "age": 200, "bio": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}'
The server answers with status 422 and this body:
{"error": "username must be at least 3 characters long; age must be between 0 and 150; bio must be at most 200 characters long"}
All three failures are listed together. Send a valid request:
curl -X POST http://127.0.0.1:3000/profiles -H "content-type: application/json" -d '{"username": "ada", "age": 36, "bio": "Loves Rust and long walks."}'
The server answers with status 201 and this body:
{"username": "ada", "age": 36, "bio": "Loves Rust and long walks."}
Checking the Boundaries
A limit is only correct if the values exactly on it pass and the values one step past it fail. The age range 0 to 150 means 0 passes, 150 passes, -1 fails, and 151 fails. The username length 3 to 30 means 3 characters pass, 30 characters pass, 2 fail, and 31 fail. These edge values are called boundaries, and they are where off-by-one mistakes hide.
The inclusive range 0..=150 gets the age boundaries right by construction: both ends are inside. A test written as age > 0 && age < 150 would get them wrong, rejecting newborns and 150-year-olds. A test written as age >= 0 && age <= 150 gets them right but spells out both comparisons by hand, which is exactly the drift the range form avoids.
The length tests use < 3 and > 30, which also get the boundaries right: a length of 3 is not less than 3, so it passes, and a length of 30 is not greater than 30, so it passes. A test written as length <= 3 would reject a three-character username that the message says is long enough.
The tests at the end of this page check all four age boundaries and the username boundaries at 30 and 31 characters. They exist because a limit that is wrong by one is wrong in the one place a real user is most likely to stand: exactly on the edge the form promised to accept.
Checking More Than One Number
A second number follows the same pattern as the first. A game profile might add a score between 0 and 100, or a settings form might add a retry count between 1 and 5. Each number gets its own test and its own message, pushed onto the same list.
// src/lib.rs
if !(0..=100).contains(&input.score) {
errors.push("score must be between 0 and 100".to_string());
}
Nothing about the collecting pattern changes when a field is added. The function grows by one if and one push, the handler stays untouched, and the joined error gains one more message when that field fails.
How a Request Flows Through the Checks
Client sends JSON body
|
v
Json extractor turns the body into CreateProfileInput
|
v
Handler calls validate_profile
|
v
Username length tested ----> message pushed on failure
Age range tested ---------> message pushed on failure
Bio length tested --------> message pushed on failure
|
v
Errors list empty?
|
yes / \ no
/ \
v v
201 created 422 with the joined messages
The diagram shows the one structural idea of this page: the tests run, the failures gather in a list, and a single decision at the end turns the list into either a success or an error. The handler never returns from inside a test. It waits until every test has had its say, and only then decides.
Testing It
Tests for range and length checks 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/profile_test.rs
use axum::{
body::Body,
http::{Request, StatusCode},
};
use tower::ServiceExt;
use validation_demo::app;
async fn post_profile(body: &str) -> (StatusCode, String) {
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/profiles")
.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 age_out_of_range_returns_422() {
let (status, body) = post_profile(r#"{"username": "ada", "age": 200}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body, r#"{"error":"age must be between 0 and 150"}"#);
}
#[tokio::test]
async fn negative_age_returns_422() {
let (status, body) = post_profile(r#"{"username": "ada", "age": -5}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(body, r#"{"error":"age must be between 0 and 150"}"#);
}
#[tokio::test]
async fn short_username_returns_422() {
let (status, body) = post_profile(r#"{"username": "ad", "age": 30}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body,
r#"{"error":"username must be at least 3 characters long"}"#
);
}
#[tokio::test]
async fn multiple_failures_are_collected_together() {
let (status, body) = post_profile(r#"{"username": "ad", "age": 200}"#).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body,
r#"{"error":"username must be at least 3 characters long; age must be between 0 and 150"}"#
);
}
#[tokio::test]
async fn boundary_values_pass() {
for (username, age) in [("ada", 0), ("ada", 150)] {
let payload = format!(r#"{{"username": "{username}", "age": {age}}}"#);
let (status, _) = post_profile(&payload).await;
assert_eq!(status, StatusCode::CREATED);
}
let ok = "a".repeat(30);
let (status, _) = post_profile(&format!(r#"{{"username": "{ok}", "age": 30}}"#)).await;
assert_eq!(status, StatusCode::CREATED);
let too_long = "a".repeat(31);
let (status, body) =
post_profile(&format!(r#"{{"username": "{too_long}", "age": 30}}"#)).await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(body.contains("at most 30"));
}
The boundary test is the most important one here. It sends the exact edge values, 0 and 150 for age and 30 characters for the username, and asserts they pass, then sends 31 characters and asserts it fails. Run them with cargo test. All five pass against the code on this page.
What the Tests Prove:
Five tests, five behaviours: too old, negative, too short, two failures at once, and the exact boundaries. If all five pass, the limits are where the messages say they are, and a client standing on an edge gets in.
Common Beginner Mistakes
Using an exclusive range for an inclusive limit
// Wrong - 150 is rejected even though the message says it is allowed
if !(0..150).contains(&input.age) {
errors.push("age must be between 0 and 150".to_string());
}
0..150 stops at 149. The message still says "between 0 and 150", so a 150-year-old gets an error that contradicts itself. The fix is 0..=150, the inclusive range, which keeps the code and the message in agreement. Whenever a limit is written in words, check that the range form includes the exact numbers the words name.
The Message and the Code Must Agree:
A validation message is a promise about what the server accepts. If the code rejects a value the message says is fine, the client cannot fix the request by reading the message. Test the boundary values to catch this, because the code compiles either way.
Counting bytes instead of characters
// Wrong - thirty accented characters count as 60 and get rejected
if input.username.len() > 30 {
errors.push("username must be at most 30 characters long".to_string());
}
.len() counts bytes. For English text the byte count and the character count agree, so this mistake passes every test written with English names and fails the first time a user types an accented letter. The fix is input.username.chars().count(), which counts what the user sees. The message says "characters", so the code must count characters.
Declaring the number too narrow
// Wrong - a negative age never reaches the handler
#[derive(Deserialize)]
pub struct CreateProfileInput {
pub age: u8,
}
With u8, a request with "age": -5 is rejected by the JSON extractor before the handler runs, and the client gets Axum's message instead of the project's own range message. Worse, the behaviour is inconsistent: 200 reaches the handler and gets the range message, while -5 gets the extractor message. The fix is i32, wide enough for every bad value the check is meant to judge.
Returning on the first failure when the list was the point
// Wrong - the age is never tested when the username fails
if length < 3 {
return Err(AppError::ValidationError(
"username must be at least 3 characters long".to_string(),
));
}
A return inside the validate function ends the whole function, so later tests never run and their failures never reach the client. The collecting pattern needs pushes, not returns: each test adds its message to the list and the function carries on. The single return belongs in the handler, after the list is complete.
Writing the message without the limit in it
// Wrong - the client cannot tell what to fix
errors.push("username is invalid".to_string());
"Invalid" tells the client nothing. A good message names the field, the rule, and the limit: "username must be at least 3 characters long". The client can fix the value without guessing, and the same message doubles as documentation of the rule. Every message on this page follows that shape for exactly that reason.
Final Complete Example
Here is everything from the page put together: the shared error type, the input struct with a username, an age, and an optional bio, the validate function that collects every failure, 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 CreateProfileInput {
pub username: String,
pub age: i32,
pub bio: Option<String>,
}
#[derive(Serialize)]
pub struct Profile {
pub username: String,
pub age: i32,
pub bio: Option<String>,
}
pub fn validate_profile(input: &CreateProfileInput) -> Vec<String> {
let mut errors = Vec::new();
let length = input.username.chars().count();
if length < 3 {
errors.push("username must be at least 3 characters long".to_string());
}
if length > 30 {
errors.push("username must be at most 30 characters long".to_string());
}
if !(0..=150).contains(&input.age) {
errors.push("age must be between 0 and 150".to_string());
}
if let Some(bio) = &input.bio {
if bio.chars().count() > 200 {
errors.push("bio must be at most 200 characters long".to_string());
}
}
errors
}
pub async fn create_profile(
Json(input): Json<CreateProfileInput>,
) -> Result<(StatusCode, Json<Profile>), AppError> {
let errors = validate_profile(&input);
if !errors.is_empty() {
return Err(AppError::ValidationError(errors.join("; ")));
}
Ok((
StatusCode::CREATED,
Json(Profile {
username: input.username,
age: input.age,
bio: input.bio,
}),
))
}
pub fn app() -> Router {
Router::new().route("/profiles", post(create_profile))
}
// 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 failing requests from the testing section and the boundary values, and compare the responses with the ones shown there. The final example behaves exactly like the smaller ones, with every check collected into one list and one decision at the end.
Summary
A range check and a length check are the same move in two costumes: measure the value, compare it against its limits, and record a message when it falls outside. The range uses contains on an inclusive range, so the code and the message name the same numbers. The length uses chars().count(), so the code counts what the user sees. The failures gather in a list, and the handler turns the list into one error or none at all.
The insight that carries forward is that validation is a list, not a single verdict. A request can be wrong in several ways at once, and the server owes the client the whole list, not just the first item it tripped over. That list is still a flat string here, with the failures joined by semicolons. The client can read it, but it cannot tell which message belongs to which field without parsing words. Giving each failure a field name of its own needs a different body shape: a map from field names to their messages.