~/nodejs/nodejs-npm-object-schema-validation-with-joi.md

Nodejs - Json object schema validation with Joi

1 min readMay 07, 2020by Gorav Singal#nodejs
// TL;DR

Use Joi's schema validation in Node.js to enforce complex constraints like mutual exclusivity, conditional required fields, and custom error messages on JSON objects.

Nodejs - Json object schema validation with Joi

Introduction

In this post, I will show how to validate your json schema validation across veriety of use-cases.

1. You want to allow only one of three params to be REQUIRED parameter

Example, you are having 5 fields. And, for three fields you want either of them to be present. Note: Success criteria is to have only one of these three fields, not 2 not 3.

Example schema validation with Joi:

const validationJoi = Joi.object({
      field1: Joi.string(),
      field2: Joi.string(),
      field3: Joi.string(),
      field4: Joi.string(),
      field5: Joi.string(),
    }).xor('field1', 'field2', 'field3')

const obj = {
  field1: "value1",
  field4: "value4",
};

const isValid = Joi.validate(obj, validationJoi);
//true

const obj2 = {
  field4: "value4",
};

const isValid2 = Joi.validate(obj, validationJoi);
//false

Note the xor above.

Note, this validation can also be used in mongoose schema validations.

const Joi = require('joi');

const mySchema = mongoose.Schema({
  name: String,
  country: String,
  email: String,
  created: { type: Date, default: Date.now }
});

mySchema.methods.schemaValidate = function(obj) {
  const schema = {
    name: Joi.types.String().min(6).max(30).required(),
    country: Joi.types.String().required(),
    email: Joi.types.String().email().required()
    created: Joi.types.Date(),
  }
  return Joi.validate(obj, schema);
}

module.exports = mongoose.model('User', mySchema);

And, in some service code you can call this method schemaValidate on MySchema object.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Mongoose - Using CRUD operations in mongodb in nodejs

Mongoose - Using CRUD operations in mongodb in nodejs

MongoDB CRUD Operations Mongoose provides a simple schema based solution to…

How to check whether a website link has your URL backlink or not - NodeJs implementation

How to check whether a website link has your URL backlink or not - NodeJs implementation

Introduction I got my seo backlink work done from a freelancer. It was like 300…

How to connect to mysql from nodejs, with ES6 promise

How to connect to mysql from nodejs, with ES6 promise

Introduction I had to develop a small automation to query some old mysql data…

WebSockets with Socket.io in Node.js

WebSockets with Socket.io in Node.js

WebSocket vs HTTP Traditional HTTP follows a request/response model — the client…

Testing Node.js — Unit, Integration, and E2E

Testing Node.js — Unit, Integration, and E2E

Testing Strategy A solid testing strategy follows the testing pyramid — many…

Redis — Caching, Sessions, Pub/Sub in Node.js

Redis — Caching, Sessions, Pub/Sub in Node.js

Why Redis for Node.js Redis is an in-memory data store that serves as a cache…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…