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 intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

ReactJS is making a controlled input of type text into an uncontrolled component with the help of a component transformation

I am encountering a situation where I fetch data from the server and set values in the state for controlled inputs. For example, if I have an input field with a value of this.state.name, I retrieve the name "Dave" from the server and set it in the state as ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

Issue with JQuery event handlers becoming unresponsive upon resizing the window

JSBin link: http://jsbin.com/4QLDC/6 Here is the JS code snippet that I have written: var toggleContent = function (event) { $(event.target).siblings().toggle(); }; var showOrHidePanels = function () { var windowHeight = $(window).height(); v ...

Showing a property only as you scroll through the page

Seeking assistance on creating a scrolling effect for a box shadow property using HTML, CSS, and JS. The goal is to have the shadow appear with a subtle transition while scrolling and then disappear when scrolling stops. Here's the code I've be ...

Leveraging passport and OAuth in conjunction with connect-redis

I am facing a challenge with implementing passport-twitter and passport-facebook for authentication in an app that utilizes Redis for Express sessions. When I remove connect-redis to store sessions in express, everything runs smoothly. However, when using ...

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 ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

What is a method to mimic the presence of JavaScript using PHP Curl?

Is it possible to parse HTML code from a webpage using PHP Curl even if there is an error message stating that JavaScript is required to access the site? Can PHP Curl be used to enable JavaScript on a webpage? ...

The regular expression functions seamlessly on the Express Route Tester tool, but encountered errors when implemented in a NodeJS environment

I recently utilized Express in a NodeJs project and I needed to create specific routes for my server: /dogs /pinguin /bear /wolf /cat /rat To test these routes, I used a regex tool () : Express Route Tester While the express route tester showed everythin ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

transform JSON data into XML format with the help of JavaScript

I need help converting a JSON object to an XML String and I'm struggling to find the right method. I recently came across a jQuery plugin called json2xml on https://gist.github.com/c4milo/3738875 but unfortunately, it does not properly escape the data ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

Instructions for activating the click function for each individual looping image

When creating a blog page, I am using PHP to loop the like button images according to the total count of posts (example: Facebook like button). The issue I am facing is that while the PHP loop is working, when I click on the first post image, only the firs ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Sending a POST request to an ExpressJS route functions well in a local environment, but encounters an HTTP 405 error when

Within my React application, I am making requests to my backend Node/Express app using axios. In my development environment, everything functions properly when I utilize a function like this: await axios.post('/createproduct', createProductBody) ...

What is the best way to assign table rows to various interfaces in typescript?

Assuming I have the interfaces provided below: export interface IUserRow { id: string, state: string, email: string, } export interface ITableRow { id: string, [key: string]: any; } export type Rows = ITableRow | IUserRow; // additio ...

When the credentials flag is set to true, the use of a wildcard '*' in the 'Access-Control-Allow-Origin' header is not allowed, as per Stormpath's guidelines

Currently, I am integrating Stormpath into my project and I want to keep the API separate from the client code (Angular, utilizing Stormpath's angular-sdk). This means that the API will be hosted on a different sub-domain compared to the client. Howev ...