Validation with Joi helps check if data is correct before using it. It stops mistakes early and keeps your app safe.
0
0
Validation with Joi in NestJS
Introduction
When you want to check user input in forms before saving it.
When receiving data from APIs and you need to ensure it has the right shape.
When you want to give clear error messages if data is missing or wrong.
When you want to avoid crashes caused by bad data.
When you want to keep your app data consistent and clean.
Syntax
NestJS
import * as Joi from 'joi'; const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().integer().min(0), }); const result = schema.validate(data);
Use Joi.object() to define the shape of your data.
Use .validate() to check data against the schema.
Examples
This schema checks that
email is a required string and a valid email format.NestJS
const schema = Joi.object({
email: Joi.string().email().required(),
});This schema requires a
password string with at least 8 characters.NestJS
const schema = Joi.object({
password: Joi.string().min(8).required(),
});This schema expects
tags to be an array of strings.NestJS
const schema = Joi.object({
tags: Joi.array().items(Joi.string()),
});Sample Program
This NestJS controller uses Joi to check the data sent to the /users POST route. If the data is wrong, it sends an error. If it is correct, it returns a success message with the user data.
NestJS
import { Controller, Post, Body, BadRequestException } from '@nestjs/common'; import * as Joi from 'joi'; const createUserSchema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required(), email: Joi.string().email().required(), age: Joi.number().integer().min(0).optional(), }); @Controller('users') export class UsersController { @Post() createUser(@Body() body: any) { const { error, value } = createUserSchema.validate(body); if (error) { throw new BadRequestException(error.details[0].message); } return { message: 'User created', user: value }; } }
OutputSuccess
Important Notes
Always validate data before using it to avoid bugs and security issues.
Joi gives detailed error messages to help fix input problems.
You can combine Joi with NestJS pipes for automatic validation.
Summary
Joi helps check data shapes and rules simply.
Use Joi schemas to describe what data should look like.
Validate data early to keep your app safe and stable.