1
votes

How to validate nested object using JOI in nodejs ("joi": "^17.3.0")

const Joi = require("joi");

const Validation = (data) => {
  const schema = Joi.object({
    details: {
      firstname: Joi.string().required(),
      lastname: Joi.string().required(),
    },
  });
  return schema.validate(data);
};

module.exports = {
  Validation,
};

req.body sample

{
    "details": {
        "firstname": "Fname",
        "lastname": "Lname"
    }
}

Validation(req.body)

Error message I'm getting ""details.firstname" is required if i'm not sending firstname property. how to get proper message like "firstname required"

2
Nope. my requirement is different - Arun M
please accept if your question solved - Mohammad Yaser Ahmadi

2 Answers

0
votes

At a quick look I found out that you are missing .keys before the nested object so it should be like this.

const Joi = require("joi");

const Validation = (data) => {
  const schema = Joi.object().keys({
    details: {
      firstname: Joi.string().required(),
      lastname: Joi.string().required(),
    },
  });
  return schema.validate(data);
};

module.exports = {
  Validation,
};

Also this validation will require firstname in the body as it is required as per your validation and if you want a custom message to show on error then it would be like this.

firstname: Joi.string().required().error(() => {
    return {
        message: 'Your custom message',
    };
})
0
votes

To have the desired output,install joi:version 14 (npm i joi@14), don't install latest version,because what you want available in version 14, Then you can do like the following code

const Joi = require("joi");

const Validation = (data) => {
  const schema = Joi.object({
    details: {
      firstname: Joi.string().required(),
      lastname: Joi.string().required(),
    },
  });
  let {error} = schema.validate(data)
  const { details } = error;
  const message = details.map((i) => i.message).join(",");
  console.log("error", message);
  return message;
};

module.exports = {
  Validation,
};