.bail() function does not function properly when used in conjunction with express-validator

While registering a new user, I require their name, email, and password. If no name is provided, there is no need for the backend to validate the email.

I believe that the use of .bail() in express-validator should handle this situation, but unfortunately, all validations are still being executed.

The route being used is:

app.post('/register', validate(createUserSchema), createUser)
;

The validate() function is as follows:

export const validate = (schemas: ValidationChain[]) => async (req: Request, res: Response, next: NextFunction) => {
    await Promise.all(schemas.map(async (schema) => await schema.run(req)));

    ...
};

The createUserSchema includes the following validations:

export const createUserSchema = [
    body('name', 'Name is required').notEmpty().bail(),
    ...

];

When my request payload looks like this:

{
    name: "", 
    email: "",
    password: ""
}

The response I receive contains the following errors:

[
    {
        "value":"",
        "msg":"Name is required",
        ...
    }
]

This is not the expected response as it should have stopped after the first validation error. Am I missing something here?

Answer №1

Decided to take matters into my own hands and answer my own question -_-

Turns out I had a misunderstanding of what a Validation Chain is in express-validator.

I mistakenly thought that multiple validation rules combined formed one chain (like an array forming a chain). That's not how it works. A chain consists of individual validation rules.

For instance

export const createUserSchema = [
    body('name').notEmpty().withMessage('Name is required').bail(), //<--- this is a validation chain
    body('email').notEmpty().withMessage('Email is required').bail()
        .isEmail().withMessage('Email is not valid').bail()
]; // <--- The entire array doesn't form a single chain (my misconception)

Gustavo Henke provided clarification here.

To achieve my desired outcome, I realized I needed to implement the .if(condition) validation method.

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

Using the .sendFile method is only compatible with the Chrome browser

I'm encountering an issue when trying to send a PDF file to a client using .sendFile from Express. Everything works perfectly in Chrome - with a Download link, Chrome saves the file; however, with a normal _blank link, Chrome opens it in a new tab. B ...

Merge Laravel, Express, and Mongodb for a powerful web application development

I am looking to develop an application and create an API using Express and MongoDB. My main web application is built on Laravel, where requests are handled by Laravel, then sent to Express, back to Laravel, and then rendered to users. In Laravel, I am no ...

Using NodeJS Express to Generate Globally Unique Request Identifiers

Can a distinctive request Id be generated for every log statement without needing to pass the logger to each method or function call? Currently using: NodeJS, Express, Winston ...

Secure a reliable result from a function utilizing switch statements in Typescript

There's a function in my code that takes an argument with three possible values and returns a corresponding value based on this argument. Essentially, it can return one of three different values. To achieve this, I've implemented a switch statem ...

Unveiling the Power of USSD Codes with Ionic Typescript: A Comprehensive Guide

Currently diving into the world of Ionic 2 Framework, I find myself on a quest to discover how to execute USSD codes in Ionic using Typescript. Any guidance or assistance from the community would be greatly appreciated! ...

In the else-branch, a type guard of "not null" results in resolving to "never."

After creating a type guard that checks for strict equality with null: function isNotNull<T> (arg: T): arg is Exclude<T, null> { return arg !== null } Testing it showed that the then-branch successfully removes null from the type. const va ...

Issue: You cannot render objects as a React child element (object found with properties {name}). If you intended to display multiple children, consider using an array instead

I have just finished creating a new Provider and now I want to test it. To do this, I am setting up a mock Component within the test file. // TasksProvider.spec.tsx const task = { name: 'New Task', } function TestComponent() { const { tasks ...

What is the best way to verify a password's strength with Joi so that it includes 2 numbers, 2 special characters, 2 uppercase letters, and 2 lowercase letters?

Is there a way to achieve this using Joi? For instance: Joi.string() .required() .min(8) .max(16) .pattern(/(?=(?:.*[a-z]){2,16}).+/) .pattern(/(?=(?:.*[A-Z]){2,16}).+/) .pattern(/(?=(?:.*[0-9]){2,16}).+/) .pa ...

What is the limitation in transmitting data as a JavaScript object rather than a JSON object?

As a newcomer to expressjs, I recently developed an application using it. Interestingly, when I send data in JSON format through POSTMAN, the application successfully returns the data. However, when I try to send data as a JavaScript object in the request ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

Mastering the proper implementation of OneToMany and ManyToOne relationships in MongoDB involves understanding and utilizing the

I am currently working on setting up a oneToMany, ManyToOne relation method and here is my progress so far (pseudocode provided below). I am using Typegoose which is essentially Mongoose with types. If you are unfamiliar with it, that's okay because t ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

Array - Modifications do not pass down to the child component

I am observing the following structure in the code: <div id="join-container"> <join-chain id="my-join-chain" [selectedColumn]="selectedColumn" (updatedStatements)=onUpdatedStatements($event)> </join-chain> <tile-ca ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

What is the proper way to define the type of an object when passing it as an argument to a function in React using TypeScript?

I'm struggling to figure out the appropriate type definition for an Object when passing it as an argument to a function in React Typescript. I tried setting the parameter type to "any" in the function, but I want to avoid using "any" whenever passing ...

How can localization be achieved in an express app using i18n + handlebars without using it to generate output HTML?

I have an Express application where I need to utilize Handlebars for creating localized email templates. The challenge here is that Handlebars necessitates a globally registered helper to translate elements within the .hbs files, while I require using a co ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

No content returned in skrill POST status response with node express

Is there a way to access the data sent in the post request to my status_url? Upon receiving a successful payment, I am getting a post request to the status_url as expected. However, I am finding that req.body, req.params, and req.query are all empty... I ...

Oops! Looks like the express command couldn't be found

I have been searching for solutions in this topic, but none of them have solved my problem. Here are my settings: Operating System: Mac OS Node.js version: v8.11.2 npm version: v5.6.0 Things I have tried: sudo npm install -g express-generator from he ...

What is the method for including a placeholder (instead of a label) in the MUI 5 DatePicker component?

I'm looking to customize the placeholder text in MUI 5's date picker. You can find the MUI 5 datepickerlink here: https://mui.com/x/react-date-pickers/date-picker/ The desired outcome:: I've tried referring to this chat, but it hasn't ...