Joi validation in Node js project

Joi Validation

  • Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It’s like a plugin play library and is easy to use.
  • Joi allow us to create blueprints of Javascript objects that ensure that we process and ultimately accept accurate data.

Install the Joi package with  the NPM

npm i joi
Write the below code in your file:
const express = require('express');
const joi = require('joi');
const app = express()
app.use(express.urlencoded({ extended: true }))
app.get("/", async (req, res) => {
    res.json({ message: 'hello world' })

apiValidate = async (req, res, next) => {
    const schema = joi.object({
        name: joi.string().required(),
        email: joi.string().email().required(),
        password: joi.string().min(4).max(10).required()
    const { error } = schema.validate(req.body)
    if (error) {
        res.json({ message: error.details[0].message })
    } else {
// applied joi validation"/new", apiValidate, async (req, res) => {
    res.json({ message: "Api is validated successfully" })

app.listen(8080, () => console.log("server is started"))
Let’s test the API:
If we enter correct details :
This way we can validate fields data

Submit a Comment

Your email address will not be published.


Select Categories