The express-validator library raises errors for fields that contain valid data

I've implemented the express-validator library for validating user input in a TypeScript API. Here's my validation chain:

  export const userValidator = [
  body("email").isEmpty().withMessage("email is required"),
  body("email").isEmail().withMessage("email is not valid"),

  body("username")
    .isEmpty()
    .withMessage("first name has to be longer than 2 characters"),
  body("username").isLength({ min: 2 }).withMessage("first name is required"),

  body("phoneNum").isNumeric().withMessage("enter a valid phone number"),

  body("password").isEmpty().withMessage("password is required"),
  body("password")
    .isLength({ min: 8 })
    .withMessage("password must be at least 8 characters"),

  body("confiremdPassword").custom((value: string, { req }) => {
    if (value !== req.body.password) {
      throw new Error("password have to match!");
    } else {
      return true;
    }
  }),
];

Now, in my auth.ts file, I check for errors like this:

 const errors = validationResult(req);
 if (!errors.isEmpty()) {
    const error: ServerError = new Error("Validation failed");
    error.status = 422;
    error.data = errors.array();
    throw error;
 }

However, the result of this validation process is quite strange as it's showing an array of all possible errors without any clear explanation...

[

{ value: '[email protected]', msg: 'email is required', param: 'email', location: 'body' }, { value: 'brrrrrro', msg: 'first name has to be longer than 2 characters', param: 'username', location: 'body' }, { value: undefined, msg: 'enter a valid phone number', param: 'phoneNum', location: 'body' }, { value: 'brorrrrrrrr', msg: 'password is required', param: 'password', location: 'body' } ] The validation is even telling me that the email is empty, despite providing the value for it.

Answer №1

Your approach needs to be flipped around.

Currently, your validation code is enforcing that the email field must be empty in order to avoid an error.

To correct this, simply include .not() before .isEmpty() in the validator.

For example:

body("email").not().isEmpty().withMessage("email is required")

Additionally, if the field is mandatory, you can also include .exists()

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

Utilizing Express routes in Node.js to rewrite URLs for proxying to Etherpad

Welcome to my first question on stackoverflow ;). What I am attempting to accomplish: My goal is to create an express route "/pad/*" that will display etherpads (etherpad lite) and allow manipulation of the pad that the user will see. For example, if the ...

What is the process for switching a button on and off?

I am attempting to add a data to an array when a button is pressed, and then remove it from the array when the button is pressed again (while also changing the button's class). <button *ngFor="#color of colors" [class.selected]="color = ...

When debugging in Visual Studio 2013, Typescript variables/fields consistently show up as undefined

What is the reason behind the properties/field variables in Typescript being consistently undefined during debugging in Visual Studio 2013? ...

The inclusion of a custom list preview with prepare in the sanity schema results in errors during the construction

I recently started working with next.js, TypeScript, and Sanity, and everything has been going smoothly so far. I have multiple schemas defined in my project and it works fine in development. The linting checks also do not show any errors. However, when I ...

Troubleshooting Vue.js: Why is .bind(this) not behaving as anticipated?

Demo: https://codesandbox.io/s/23959y5wnp I have a function being passed down and I'm trying to rebind the this by using .bind(this) on the function. However, the data that is returned still refers to the original component. What could I be missing h ...

Keystrokes may not consistently register in Firefox

I created a compact web application where users can interact by clicking on a button to trigger a modal dialog. Within this dialog, users have the ability to choose from various options. To enhance user experience, I implemented the utilization of the jQue ...

Shuffle array elements in JavaScript

I need help with manipulating an array containing nested arrays. Here's an example: const arr = [[red,green],[house,roof,wall]] Is there a method to combine the nested arrays so that the output is formatted like this? red house, red roof, red wall, g ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

Rapidly generate VueJS templates for quick display

Is there a way, similar to KnockoutJS, to easily render content from a template using an ID? <script type="text/html" id="template-example"><span>Hello world!</span></script> <div data-bind="template: &a ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Is there a way to make model.save() return a value?

I'm currently exploring node.js and attempting to store data in MongoDB using mongoose. My goal is to return false in case of an error during the save operation (for example, if a user with the same name already exists). The issue lies in the sequence ...

Changing a PDF file into binary form using Node JS and Express

I have a web application that allows users to upload PDF files. Once uploaded, the file needs to be converted into binary data in the backend without being saved in a temporary folder, so it can be stored in a database. While I am able to upload and read ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

Setting up a variable within a v-for iteration in Vue JS

I'm currently facing a challenge in finding a solution to what appears to be a simple problem. Within a template, I am using a v-for loop to generate some content. In this content, I need to execute a function to check if the contentID matches an ID ...

Tips for implementing manual gravity effects on objects in cannon.js?

Is there a proper way to control gravity on individual objects without compromising collision events or rotation velocity? I came across this issue but seeking a more comprehensive solution. In my situation, I need player physics to function normally, wh ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

How can JavaScript be utilized to iterate through regex matches and divide a string into an array of segments separated by hyperlinks?

After receiving a string from an api, it appears like this: "If you <a href='https://example.com'>Click here</a> then <a href='https://example.net'>Click here</a>." I aim to construct an array that mir ...

The height of my row decreases when I implement the z-index for a hover effect

Hey there! I'm currently working on creating a hover effect for my cards using Bootstrap and z-index. However, I've run into an issue where the z-index works fine when I hover over the cards, but the row loses its height. I tried adding a height ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

Is there a way to rotate label text on a radar chart using chart js?

I am working with a Chart js radar diagram that contains 24 labels. My goal is to rotate each label text by 15 degrees clockwise from the previous one: starting with 'Label 1' at the top in a vertical position, then rotating 'Label 2' ...