What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly.

exports.postValidatorCheck = [
  check("title", "The title must not be empty").isEmpty(),
  check("title", "The length of the title should be greater than 10").isLength({
    min: 10,
    max: 1500
  }),
  function(req, res, next) {
    let errors = validationResult(req);
    console.log(errors);
    if (!errors.isEmpty()) {
      const firstError = errors.errors.map(err => err.msg)[0];
      return res.status(400).json({ error: firstError });
    }
    next();
  }
];

JSON file:

{
"title":"",
"body":"This is a new Post"
} 

No error

JSON file

{
"title":" ",
"body":"This is new post"
}

Error as expected.

Answer №1

Utilizing the negative in validation:

ensure("title", "Please provide a non-empty title").not().isEmpty()

By implementing this, it guarantees that the title is not empty as per your intention.

Answer №2

Initially, an empty string is represented by "". However, if a string contains spaces like in " ", it is not considered empty. In case you want to treat any whitespace as empty, consider using a regular expression solution.

Regarding the specific problem you are facing, make sure to check for not().isEmpty() instead of just isEmpty().

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

Making HTTP requests with axios in Node.js based on multiple conditions

I'm facing an issue with making get calls using axios to both activeURl and inactiveURl. The goal is to handle error messages from the activeUrl call by checking data from the inactiveUrl. However, I keep receiving error messages for the inactiveURL e ...

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Maintaining aspect ratio of canvas while ensuring responsiveness

Currently, I am working on a drawing app and have come across an issue that has been challenging for me to resolve. The dilemma lies in resizing the canvas of sketches from the original resolution of 1280 x 720 to the maximum size possible upon opening the ...

Issue with PrimeNG Calendar not updating date value within modal

While using the PrimeNG Calendar control, I encountered an issue. Even though I am able to select and store dates, when I try to fetch dates from a database and update the Modal, I receive the following error message: <p-calendar [(ngModel)]="bi ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

Guide to formatting JSON correctly in Java

private List<String> itemsInCart = new ArrayList<>(); private List<String> itemObjectsInCart = new ArrayList<>(); @CrossOrigin @GetMapping(value = "/cartitems") public List<String> getItemsInCart(@RequestParam("buyerId") Int ...

Error: Trying to set a value to an undefined object in the bind() method

I am currently working on implementing a listener for my video player in order to update the input range on some custom controls. However, I have encountered an issue with an error message that states Uncaught ReferenceError: Invalid left-hand side in as ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

Refreshing an external file in Node.js at regular intervals

Seeking guidance on loading external files in node. I'm currently working with an external JSON file that houses some configuration settings, and this file gets updated by an outside process every 10 minutes. How can I automate the reloading of this ...

Use jQuery to switch back and forth between the login and registration forms on a single

I've set up two forms, one for login and one for registration, with the default view showing the login form. There's a link that says "Don't have an account?" and when it's clicked, the registration form will display while the login for ...

Determine the number of rows in an Excel spreadsheet using JavaScript

Currently, I am working on a codeigniter project where I need to upload an Excel file. However, before uploading the file, I want to display the number of records it contains. To achieve this, I decided to create a function within my script and then call t ...

Animate an svg icon to follow a designated path as the user scrolls

I am currently working on a project that involves animating a bee svg icon as the user scrolls through the website. The bee starts at the top and fills in a grey color line with pink as the user moves forward, and moves backward as the user scrolls back. Y ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Demonstrate still behaviour

Currently, I am running a server with express. Within my folder structure, I have: - public -- image1.png -- image2.png -- image3.png - src -- app.js Inside app.js, I set up the server using express and use the following code: const app = express(); app ...

Upon successfully logging in via an API, I received a JSON response. Now, I want to display the length of the arrays as the count for my notification icon. Any suggestions on how I can

I have implemented the following code to fetch JSON data in my app. The JSON response includes user details and notifications. { "user_id": 1, "user_name": "Mr Admin", "api_token": "6S3gRnPy55JKWyiOF7SwtYO12waZ8 ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

Activate and deactivate animation using one button with jQuery

Looking for a solution using Jquery. Can you animate an element when clicking a button and then stop the animation with the same button? Here is an example code snippet in JavaScript: $('<div>').css({ 'width':'200 ...