Validate inputs
Rules on the entity flow into every edge that decodes a post — a malformed body becomes a structured 400 before the handler runs.
The rules are already on the entity, where nestrs g resource wrote them on
Declare the entity. The #[crud] macro’s generated
POST /posts handler takes Json<CreatePost>, and the edge holds every
argument it decodes to the rules its type declares, so every request body is
checked before PostsService::create runs.
By the end of this page, curl returns a structured 400 for an empty
title, and a well-formed body persists a post through the database you
wired on the previous page.
No handler edit required
Section titled “No handler edit required”nestrs g resource left impl PostsController {} empty, and you read it on
Expose over HTTP. That is
not a shortcut — for a bare CRUD feature, the macro is the handler.
#[crud] emits create and update methods whose body is a plain
Json<…>:
#[post("/")]async fn create(&self, __body: Json<CreatePost>) -> Result<Created<Json<Post>>> { // Creatable::create, then a `201` naming the row it made}There is nothing to wrap: the rules travel with the type. When you later
write create by hand on a richer feature, Json(input): Json<CreatePost>
is validated exactly as the generated one is — and so is a GraphQL mutation,
a WebSocket message or an MCP tool taking a CreatePost.
The crate driving this page is
nest-rs-pipes —
it holds the check every edge runs on what it decoded, the transport-agnostic
Pipe trait, and the Piped carrier a transform binds through.
Where the rules live
Section titled “Where the rules live”The rules are on the entity, in Declare the entity:
#[expose(input(create, update), validate(length(min = 1)))]pub title: String,
#[expose(input(create, update), validate(length(min = 1)))]pub body: String,#[expose] carries the validate(...) attribute through to
CreatePost and UpdatePost. No second declaration on the
DTO; the entity is the single source.
The bad-body response
Section titled “The bad-body response”A malformed body comes back as an RFC 9457 application/problem+json
400 with the structured field errors validator produces riding as an
errors extension member.
AuthnGuard runs before the validation, so both calls below carry the
$TOKEN you signed on Persist through Postgres — drop
the header and the answer is a 401 that never reaches the rules this page is
about.
$ curl -i -X POST http://localhost:3001/posts -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"title":"","body":"World"}'HTTP/1.1 400 Bad Requestcontent-type: application/problem+json
{ "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "validation failed", "code": "INVALID_ARGUMENT", "errors": { "title": [{ "code": "length" }] }}The failing field surfaces in errors. The client can render per-field
messages from errors.<field>[].code without parsing the human message.
An entry carries a message only when the rule sets one
(validate(length(min = 1, message = "…"))), and never the rule’s
parameters, which can hold the rejected value: it never echoes back.
The good-body path is unchanged
Section titled “The good-body path is unchanged”A well-formed body flows straight through — a body keeping its rules is handed over untouched — and, with the database wired on the previous page, the handler persists the post and returns it.
$ curl -i -X POST http://localhost:3001/posts -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"title":"Hello","body":"World"}'HTTP/1.1 201 Createdlocation: /posts/018f…content-type: application/json
{"id":"018f…","title":"Hello","body":"World","created_at":"2026-…","updated_at":"2026-…"}A 201 with the created row, and the Location that names it — the body
cleared validation and the service committed it in a transaction. The check
only ever intercepts the malformed case.
Two failure modes worth the distinction
Section titled “Two failure modes worth the distinction”| Failure | Status | Trigger |
|---|---|---|
| The body isn’t valid JSON | 400 | Json rejects before any rule runs |
| The body parses but a field is wrong | 400 with errors | CreatePost’s rules reject after extraction |
Both are 400; the second carries the structured errors member a
client form binds to. The handler never sees either.
A custom rule with #[validate(custom)]
Section titled “A custom rule with #[validate(custom)]”When validator’s built-in rules aren’t enough, point the entity
field’s validate(...) at a function — no hand-written DTO, the rule
rides through to CreatePost / UpdatePost exactly like the built-in
ones:
#[expose( input(create, update), validate(length(min = 1), custom(function = "not_a_placeholder_title")))]pub title: String,use nest_rs::pipes::validator::ValidationError;
fn not_a_placeholder_title(title: &str) -> Result<(), ValidationError> { if title.eq_ignore_ascii_case("todo") { return Err(ValidationError::new("placeholder_title")); } Ok(())}The function returns validator’s own error type, which the framework
re-exports at the release it derives with, so the feature crate’s manifest gains
no line.
The error code ("placeholder_title") surfaces in errors.title[].code
— same shape, same client contract.
What you have now
Section titled “What you have now”- A
POST /postsroute that rejects malformed bodies before they reach the service — wired by#[crud], not by hand. - A structured
400body with one entry per failing field, codes stable enough to assert on. - A pattern you carry forward: entity rules → every handler, generated or written by hand, that takes the input type.
Going further
Section titled “Going further”- Test it end to end — the next step: lock the round-trip down with an e2e suite.
- Pipes — the reference page for validation at the edge and the pipe layer.