Joi mistakenly demanding certain fields that should not be mandatory

I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory.

posts validation

module.exports.postsValidation = (data) => {
  const schema = Joi.object({
    textfield: Joi.string().max(280),
    picture: Joi.string(),
  });

  return schema.validate(data);
};

posts.js (where validation is used)

router.post("/create", authenticateToken, async (req, res) => {
  try {
    if ((req.body.textfield == "") & (req.body.picture == "")) {
      return res.status(400).json("Fill one of the fields");
    }

    const { error } = postsValidation(req.body);
    if (error) return res.status(400).json(error.details[0].message);

    // Creating a new post
    const newPost = new Post({
      textfield: req.body.textfield,
      picture: req.body.picture,
      ownerId: req.user._id,
    });

    // Saving the new post
    await newPost.save();

    res.json(newPost);
  } catch (error) {
    res.sendStatus(500);
  }
});

The error message indicates that:

[Error [ValidationError]: "picture" is not allowed to be empty] {
  _original: { textfield: 'sssss', picture: '' },
  details: [
    {
      message: '"picture" is not allowed to be empty',
      path: [Array],
      type: 'string.empty',
      context: [Object]
    }
  ]
}

If anyone could help shed some light on what might be causing this issue, I would greatly appreciate it.

Answer №1

The reason behind this issue is that the prop picture being sent from the front-end is an empty string ''. To address this, you can include .allow('') in your validation for the picture field: picture: Joi.string().allow(''). This will allow saving an empty string in the database. Alternatively, you can modify the front-end to not send the picture prop at all when the string is empty.

Answer №2

It's always good to account for the possibility of a null value

module.exports.postsValidation = (data) => {
  const schema = Joi.object({
    textfield: Joi.string().max(280),
    picture: Joi.string().allow("", null),
  });

  return schema.validate(data);
};

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

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

What is the proper way to parse an array of JSON objects?

Here is the data I need help with: var information = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "llll. ...

Access previous value in Vuejs onchange event

In the code snippet below, how can I retrieve the previous value of the model that has been changed, specifically the age in vuejs? var app = new Vue({ el:"#table1", data:{ items:[{name:'long name One',age:21},{name:'long name Two&a ...

Creating Object of Objects in TypeScript: A Comprehensive Guide

Assuming I have a structure similar to this: interface Student { firstName: string; lastName: string; year: number; id: number; } If I intend to handle an array of these structures, I can simply specify the type as Student[]. Instead of utilizin ...

Issue with importing React: 'Module not found: Unable to locate'

I've organized my React project with a folder system, as shown in the screenshot below: https://i.stack.imgur.com/Rl9Td.png Currently, I'm attempting to import from context.js, located in src/context.js, into index.js, found in src/components/K ...

The React Route Component is responsible for managing all routes that start with "/", with the exception of the "/login" route

When accessing the /login route, the Dashboard component is also rendered. However, I need to exclude the Dashboard component while on the Login page. The exact attribute isn't suitable in this case because the Dashboard has nested paths such as /das ...

Simple way to automatically reload your script using an npm server

Testing out a sample javascript code snippet. Locating a script named simple.js in the demos directory. Executing the demo using the command yarn build-demos && http-server demos/ The script simple.js is compiled to simple_bundle.js and the serv ...

How can I break down an object with hyphenated key names?

Attempting to perform object destructuring on the following: { name: "Bryan", last-name: "Enid" } However, trying to destructure it like this is not successful: const {name, last-name} = req.body Is there an alternative method to destructure this ...

Getting form field values with JQuery

I am currently facing an issue with a form field in HTML. Here is the code snippet: <form id="tasklist"> <input type="text" id="name" ...></input> ... additional form elements go here ... </form> Although I am trying to retrie ...

Implementing mixin functions in vue.router routes with Vue.js

Is there a way to dynamically change the title of the window based on each route? I have included a meta: { title: ... } object in each child object within the routes: []. Here is an example: routes: [ { path: 'profile/:id', name: 'Prof ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

SyntaxError: An invalid character was encountered (at file env.js, line 1, column 1)

This marks my debut question so kindly indulge me for a moment. I recently stumbled upon a guide that outlines how to dynamically alter environment variables in a React project without the need for re-building. You can find the guide here. The method work ...

Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language. Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in b ...

Utilizing Selenium JavaScript to insert a cookie into a request

Trying to add a cookie to the request in Selenium using JavaScript. I followed the documentation at this link, but my code snippet doesn't seem to pass any cookies to the PHP script below on the server. Here is the client-side JavaScript code: var w ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button? Below is the code snippet I have been working on, but it only r ...

Error occurred during railway deployment, causing the build to fail

Currently, I am attempting to deploy a basic notes app on Railway as part of a course challenge. However, every time I try to deploy it, I encounter the following error message: #13 ERROR: executor failed running [/bin/bash -ol pipefail -c npm run build]: ...

Issue with MUI toggle switch not updating display and value upon clicking once

I'm currently experiencing issues with a Material UI toggle switch in my project. Initially, when the component loads, the console log displays the correct value. However, when I toggle the switch from 'yes' to 'no', the visual cha ...

What sets the Test Deployment and Actual Deployment apart from each other?

I have been developing a web application using Google App Script and I currently have multiple versions of the same web app with various fields. Interestingly, when I run one version through a test deployment, it displays correctly as expected based on th ...