Validation of a Joi field based on a specific list of options in another field

I need to validate a field within an object based on specific values in another field. Let's say I have two fields, field1 and field2. The possible values for field1 are A, B, C, D, E, F, H, I. If field1 has the value of A, B, or C, then field2 should be null. How can I achieve this? I believe the syntax should be similar to the example below, but I'm not sure how to implement it correctly.

const mySchema = Joi.object({
   field1: Joi.string().valid('A','B','C','D','E','F','H','I').required(),
   field2: Joi.when('field1', is: <A or B or C or H> then: <field2 should be null> otherwise: Joi.date().required())
});

Note: I am working with "@hapi/joi": "^17.1.1"

Answer №1

After some trial and error, I was able to figure it out using the following code:

const Joi = require("@hapi/joi");

const schema = Joi.object({
    field1: Joi.string().valid('A', 'B', 'C', 'D', 'E', 'F', 'H', 'I').required(),
    field2: Joi.when('field1', {
        is: Joi.string().valid('A', 'B', 'C', 'H'),
        then: Joi.valid(null),
        otherwise: Joi.date().required(),
    }),
});

const validation = [schema.validate({ field1: 'B', field2: null }), schema.validate({ field1: 'E', field2: null }),
                    schema.validate({ field1: 'E', field2: Date() }), schema.validate({ field1: 'A', field2: Date() })];

validation.forEach((v)=>{
    if(v.error){
        console.log(JSON.stringify(v.error));
    }else{
        console.log(JSON.stringify(v.value));
    }
});

The results of the output are shown below:

{"field1":"B","field2":null}
{"_original":{"field1":"E","field2":null},"details":[{"message":"\"field2\" must be a valid date","path":["field2"],"type":"date.base","context":{"label":"field2","value":null,"key":"field2"}}]}
{"field1":"E","field2":"2020-05-20T12:26:48.000Z"}
{"_original":{"field1":"A","field2":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)"},"details":[{"message":"\"field2\" must be [null]","path":["field2"],"type":"any.only","context":{"valids":[null],"label":"field2","value":"Wed May 20 2020 13:26:48 GMT+0100 (West Africa Standard Time)","key":"field2"}}]}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute the node server and webpack simultaneously by utilizing the package.json file

I recently finished a todo app project after following along with this informative video: Excellent MEAN Stack Tutorial: Angular, Node/Express, Webpack, MongoDB, SASS, Babel/ES6, Bootstrap In the tutorial, specifically at minute 19:18 on this link, the i ...

What is the reference point for 'this' in Mongoose query middleware and pre-find hooks?

After diving into the world of mongoose query middleware, I've come to realize that using this within a query middleware function actually refers to the query object itself. Despite this knowledge, I still find it challenging to imagine what the quer ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

"Running the command 'npm install' may introduce new and unfamiliar files into your

When I attempt to use npm install uuid to update the dependencies in my package.json file, it seems to add a variety of JavaScript files such as uuid.cmd and uuid.ps1. Oddly enough, the uuid dependency is not included in the package.json file afterwards. ...

Having trouble resolving '___' from the 'home' state? Dealing with an angular ui-router complication?

I am a newcomer to angular and currently following the instructions outlined in this tutorial: https://scotch.io/tutorials/angularjs-multi-step-form-using-ui-router However, I am facing challenges while injecting this module into an existing module. Des ...

Handling a setTimeout within an API endpoint

I am working on implementing a delay for an API call by using setTimeout. The goal is to return res.status(200).json(response) after a 2-second delay upon success. exports.someEndpoint = function(req, res) { return request.post({ url: //etc ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Questions about setting up a local development environment for Angular.js

After completing a few tutorials on Angular.js, I was eager to start building projects from scratch locally. However, despite my efforts, I have not been able to successfully set up my local development environment. I tried copying the package.json from A ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

Is your current Angular 2 project in need of data retrieval from a SQL server?

Currently, I am facing a challenge with my Angular 2 application as I am unable to connect and send queries to an existing SQL server. It has come to my attention that in order to achieve this, I need to create a RESTful API using 'express.js'. I ...

What is the best way to combine a React App and an Express App in order to deploy them as one

After successfully creating an Express and MongoDB API and connecting it to my React Application, I encountered a situation during deployment. It seems that I need to deploy both projects separately, which means I would need two hosting plans for them. H ...

Two users are attempting to book two different appointments at the same time in Node.js utilizing MongoDB. However, only one user will

Within the functionality of my application, users have the ability to reserve a booking for time XYZ, as long as that specific time slot is still available. However, imagine if another user is also trying to book time XYZ simultaneously with the first us ...

Passport authentication leading to incorrect view redirection in Express

I'm struggling to understand why the URL is updating but leading to the incorrect view. Once a user is authenticated with passport, the URL changes to my code (/clients) but it redirects back to the homepage view. After authentication, I want the us ...

Decoding the information received from Socket.IO within the Flash client

When utilizing server node.js and module Socket.IO, data transmission is handled as shown below: var tests = [555, 777]; client.send("Test string"); //first message client.send({tests:tests}); //second message If the data sent is a text string (fi ...

Improved Node.js algorithm designed to identify anagrams of a specific string in an array. The approach must not rely on generating all possible subsets to find the anagram of the string

I am looking to create a collection of anagram pairs within an array. The input will consist of the initial array of strings. For example: let inputArray = ["abcd", "dbac", "adfs", "adsf", "bDca"]; This program should consider the case of the letters, m ...

What is the best way to incorporate the req parameters into the SQL query?

The Situation In the process of developing a node app, I encountered an issue with injecting the result of multiple SQL queries into an EJS view. Initially, I had successfully implemented a single query within the app.get() function. This query retrieved ...

Is there a way for me to identify which dependencies are relying on a specific package within my node_modules directory?

A new feature on Github now notifies users about security vulnerabilities in their package-lock.json. While I want to address these issues, it's challenging to identify which top-level package in my package.json needs an upgrade since most listed pack ...

How to Populate .handlebars Templates with Multiple SQL Results in Express

As a newcomer to the world of Express and Node.js, I am eager to understand how to display multiple SQL results on different elements of a web page. Though it may be a simple question for some, I am unsure how to proceed and would greatly appreciate any g ...

Issue with Heroku deployment: Express module not detected

I'm currently facing an issue while trying to deploy my Node.js app that includes some getter and setter functions. Despite selecting the Node.js environment on Heroku and providing all necessary environment variables, I keep encountering errors relat ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...