How can you make nested JSON values optional in Joi Validation?

As I work on my API, I encounter a nested JSON structure that serves as the payload for the endpoint. Here is an example of what it looks like:

{"item_id":"1245",
"item_name":"asdffd",
"item_Code":"1244",
"attributes":[{"id":"it1","value":"1"},{"id":"it2","value":"1"}],
"itemUUID":"03741a30-3d62-11e8-b68b-17ec7a13337"}

When it comes to validating this payload using Joi, here is what my validation logic looks like:

validate: {
                    payload: Joi.object({
                        item_id: Joi.string().required(),
                        item_name: Joi.string().required(),
                        placeId: Joi.string().allow('').allow(null),
                        itemUUID: Joi.string().allow('').allow(null),
                        item_Code: Joi.string().required().allow(null),
                        attributes: Joi.alternatives().try(attributeObjectSchema, attributeArraySchema).optional()
                    })
                }

In the validation process, I define two schemas. The first one caters to individual attributes as objects, and the second one handles arrays of attributes:

const attributeObjectSchema = Joi.object({
    id: Joi.string().optional(),
    value: Joi.string().optional()
}).optional();

The second schema, which deals with arrays of attributes, looks like this:

const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();

Now, if I attempt to send a payload where all values in the "attributes" array are empty, Joi throws an error message:

"message": "child \"attributes\" fails because [\"attributes\" must be an object, \"attributes\" at position 0 fails because [child \"value\" fails because [\"value\" is not allowed to be empty]]]",
  "validation": {
    "source": "payload",
    "keys": [
      "attributes",
      "attributes.0.value"
    ]

This error prompts me to reevaluate my validation criteria. How can I modify my Joi validation code to accept a payload where attribute values are empty strings like so:

 "attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]

Answer №1

Try implementing it in this way

attributeArraySchema.customAttributes = [];
attributeArraySchema.customAttributes = [
    {"id":"CA1","value":""},
    {"id":"CA2","value":""}
];

Answer №2

After some troubleshooting, I successfully tackled this issue by making a key change in the schema definition as shown below:

const updatedAttributeObjectSchema = Joi.object({
    id: Joi.string().optional(),
    value: Joi.string().allow('').allow(null)
}).optional();

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

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

Maximizing the potential of .delegate in combination with .closest

$('.inputRadio').parent().click(function (e) { //implement delegate method here }); Looking for assistance on how to integrate the delegate method in the provided function. Any suggestions? ...

Sustained concentration on NextJS

As I embark on my journey of building my very first NextJS site, I have encountered a strange anomaly. Within my site's header, I have incorporated several <Link /> components that serve as links to different pages of my site. These links are a ...

Managing sessions and cookies for Firefox forms

On my webpage, there is a poll form where users can vote and see the results through an ajax request. When a user votes, a cookie is created to prevent them from voting again upon returning to the page. However, I have encountered an issue with Firefox wh ...

Trouble with Jackson JSON parser: Resolving a problem with ManyToMany relationships

We are currently utilizing Spring MVC along with the Jackson parser for converting Java objects to JSON. Within our application, we have two entities that are in a many-to-many relationship: Project Service A Project contains a list of serv ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Data is not being displayed in Laravel's Yajra DataTable when using the Infyom package

After diving into Laravel 8 with Yajra DataTable, I decided to explore Infyom Laravel-Generator, a promising package. My initial attempt at creating a test app with a Yajra DataTable seemed successful at first glance. However, after adding a record to the ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

Is there a way to raise an error in React Native and make it visible?

I am working on a functional component where I need to call a method from another .js file. The method in the external file intentionally throws an error for testing purposes, but I want to propagate this error up to the functional component's method. ...

Transferring a list from MVC ViewBag to JavaScript

I have a situation where I am passing a list of users from my controller to the view using the ViewBag. Now, I also need to pass this same list to the JavaScript on the page. One way I thought of doing this is by iterating through the list with a foreach l ...

Collapse the active panel on a jQuery accordion with a click event

I'm currently utilizing the Simple jQuery Accordion created by CSS-Tricks, and I am seeking guidance on how to enable the active panel to close when clicking on the link within the dt element. The scenario where I am implementing this is as a menu in ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

Tips on creating an onclick function in javaScript and linking it to innerHTML

let a = 10; let b = 15; document.getElementById("text").innerHTML = '<div onclick=\'testing("'a + '","' + b + '") > text </div>'; Welcome, I am new to this ...

How can PostgreSQL efficiently identify the existence of a JSON value within a dataset, such as using indexing

I'm looking to retrieve rows that have a json value of '111' id json 1 {"1":"111", "2":"222"} 2 {"1":"111", "3":"333"} 3 {"4":"444", "2":"222"} 4 {"4":"666", "2":"111"} 5 {"1":"777", "3":"888"} ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

Using JSON in combination with any client or server programming language allows for seamless

Is it possible to use any language as server and client sides if I choose JSON as the data exchange format? I am currently working on a web application using PHP and jQuery. My server delivers responses in JSON format, and now I want to develop an Android ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Is there a way for me to send a form containing pre-existing data from a different page?

Seeking advice: I realize that utilizing jQuery's ajax function may be the simplest approach, however I am facing an issue with the form field names. The var_dump below displays the typical values submitted by the form using test data. It appears that ...

Store the MySQL query results into a multidimensional array

#UPDATED I found this interesting table: product_img_detail Table I'm trying to convert the results into a JSON array like this: { "selectedColor": "black", "black": { "thumb": { "image1": "../img/e-commerce/pr ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...