Validation Pipe in Moost
With Moost’s validation pipe, powered by Zod, you can define data schemas and enforce them through decorators rather than writing validation logic manually. Instead of inline validation checks or separate schema files, Moost allows you to annotate your classes (DTOs) and parameters directly with Zod-based decorators, turning validation into a declarative, easy-to-manage process.
New to Moost Pipelines? Read the Introduction to Moost Pipelines to learn more about Moost’s pipeline system.
How It Works
DTO Classes with
@Validatable()
:
You first create a Data Transfer Object (DTO) class and mark it as@Validatable()
to indicate that Moost should run it through the Zod validation pipe.Zod Decorators on Properties:
Decorators like@IsString()
,@IsEmail()
, or@Min()
(among many others) let you declare Zod schemas at the property level. These decorators transform your class definition into a Zod schema.Applying the Zod Pipeline:
Once your DTO is annotated and@Validatable()
is set, the Zod pipeline is triggered during the Resolve and Validation Pipe stages. Any incoming data that maps to these DTOs (e.g., request bodies, parameters) gets validated automatically. Invalid data raises a Zod error before your handler executes.
Example
Suppose you’re building an endpoint to create a new user. You can define a DTO class as follows:
import { Controller, Post, Body } from 'moost'
import { Validatable, IsString, IsEmail, Min } from '@moostjs/zod'
// Mark this class for validation
@Validatable()
class CreateUserDto {
@IsString()
@Min(3)
username!: string
@IsEmail()
email!: string
}
@Controller('users')
class UserController {
@Post('create')
createUser(@Body() data: CreateUserDto) {
// If we reach here, 'data' already passed Zod validation
return `User ${data.username} created with email ${data.email}`
}
}
What’s happening here?
@Validatable()
signals that theCreateUserDto
should be transformed into a Zod schema.@IsString()
and@IsEmail()
define the required data formats, while@Min(3)
ensuresusername
is at least 3 characters long.- When you send a POST request to
/users/create
, Moost’s validation pipe checks the request body against this Zod schema. If it’s invalid, you get a clear error before the handler runs.
Applying the Zod Pipeline
To enable this validation, you need to apply the Zod pipeline to your Moost app (or per controller/method if desired):
import { Moost } from 'moost'
import { ZodPipeline } from '@moostjs/zod'
const app = new Moost()
app.applyGlobalPipes(ZodPipeline())
With these steps in place, the validation pipe automatically ensures all decorated DTOs and parameters are checked, improving data consistency, reducing boilerplate, and making error handling more straightforward.
Read Enabling Other Pipes to learn more ways to apply a pipeline.