Let's add validation using Joi to our existing Node.js + Express blog API, specifically for creating articles.
📦 Step 1: Install Joi
npm install joi
📁 Step 2: Create a Middleware File
Create a file: middlewares/validateArticle.js
const Joi = require('joi');
// Define the schema
const articleSchema = Joi.object({
  title: Joi.string().min(3).max(100).required(),
  content: Joi.string().min(10).required(),
  author: Joi.string().min(3).required()
});
// Middleware to validate request body
function validateArticle(req, res, next) {
  const { error } = articleSchema.validate(req.body);
  if (error) {
    return res.status(400).json({ error: error.details[0].message });
  }
  next();
}
module.exports = validateArticle;
🧠 What this does:
- 
It checks that:
- 
titleis a string between 3–100 chars - 
contentis at least 10 chars - 
authoris required and at least 3 chars 
 - 
 If validation fails, it sends a 400 response with a message like:
  "title" is not allowed to be empty
🧪 Step 3: Use the Middleware in the POST Route
In your route file (or server.js, depending on your structure):
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Article = require('./models/article');
const validateArticle = require('./middlewares/validateArticle');
const app = express();
app.use(express.json());
app.use(cors());
// POST with validation middleware
app.post('/api/articles', validateArticle, async (req, res) => {
  try {
    const newArticle = new Article(req.body);
    const savedArticle = await newArticle.save();
    res.status(201).json(savedArticle);
  } catch (err) {
    res.status(500).json({ error: 'Server error while creating article' });
  }
});
✅ Example of a Valid Request
{
  "title": "How to Use Joi",
  "content": "Joi is a powerful schema description and validation tool...",
  "author": "Xavier"
}
❌ Example of Invalid Request
{
  "title": "",
  "content": "short",
  "author": ""
}
Response:
{
  "error": "\"title\" is not allowed to be empty"
}
    
Top comments (0)