Why is the Express validator failing to work with the posted value?

I have come across an issue with my current code. Everything is working fine, but I need to access req.body.type in the createValidationFor function. However, when I try to access it, the validation stops working and I can't figure out why.

router.post(
        '/login',
        createValidationFor('email'),
        checkValidationResult,
        (req, res, next) => {
            res.json({ allGood: true });
        } );

function createValidationFor(type) {

    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];

        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default:
            return [];
    }
}

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    }

    res.status(422).json({ errors: result.array() });
}

In a modified version of the code, I am attempting to access req inside the createValidationFor function. However, after doing so, the validation stops working:

router.post(
    '/login',
    createValidationFor,
    checkValidationResult,
    (req, res, next) => {
        res.json({ allGood: true });
    }
);

function createValidationFor(req, res) {
    var type = req.body.type;
    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];

        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default:
            return [];
    }
}

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    }

    res.status(422).json({ errors: result.array() });
}

Answer №1

Ensure that your function createValidationFor does not require the req, res, next parameters because it is not designed to be a middleware function. Instead, it should solely focus on generating and returning the appropriate validation chain based on the provided type parameter (e.g., type = 'email'). The responsibility of handling all middleware operations lies with the checkValidationResult function: it identifies any validation errors and either sends an error response or proceeds with next().

function createValidationFor (type) {
    switch (type) {
        case 'email':
            return [
                check('email').isEmail().withMessage('must be an email')
            ];
        case 'password':
            return [
                check('password').isLength({ min: 5 })
            ];
        default: 
            return [];
    };
};

function checkValidationResult(req, res, next) {
    const result = validationResult(req);
    if (result.isEmpty()) {
        return next();
    };
    res.status(422).json({ errors: result.array() });
};

router.post(
    '/login',
    createValidationFor('email'),
    checkValidationResult,
    (req, res, next) => {
        res.json({ allGood: true });
    }
);

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

Customize your Android WebView to show specific sections of a website

Struggling to display a specific part of a webpage in my webview, despite trying numerous solutions. class ActionFragment : Fragment() { class MyWebClient : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

Incorporate React into current Node express application by utilizing a content delivery network (CD

I'm currently in the process of developing a web application utilizing both Node and React. Instead of having separate Node and React applications, I decided to integrate React directly into my existing setup. To achieve this, I attempted importing th ...

The transparency level of materials in THREE.js

When using the lambert shader, I encountered an issue with setting the material. In the example provided, it sets the material as follows: this.material.uniforms.emissive.value = new THREE.Color( Math.random(), Math.random(), Math.random()); Prior ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

How do I remove all elements from the Canvas in R3F?

I need a way to clear all models from the Canvas with just one click and then switch over to a new Canvas. I want to make sure that all items are removed from memory before making the change. Is there a way to accomplish this? return ( <div clas ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

Is a missing dependency causing an issue with the React Hook useEffect?

I've encountered an issue with the following code snippet, which seems to only depend on [page]. Despite this, I am receiving the error message: React Hook useEffect has a missing dependency I've come across similar discussions suggesting to com ...

Remove image files from a directory with jQuery without relying on PHP or AJAX

Did you know that JQuery code is capable of executing unlink operations like PHP without using AJAX or a PHP file? For instance, if you wish to delete or unlink the file "aaa.jpg" located in the folder www.myproject.com/images/, you can achieve this by s ...

Adjusting the width of a nested iframe within two div containers

I am trying to dynamically change the width of a structure using JavaScript. Here is the current setup: <div id="HTMLGroupBox742928" class="HTMLGroupBox" style="width:1366px"> <div style="width:800px;"> <iframe id="notReliable_C ...

Now that connect no longer utilizes the parseCookie method, what is the alternative method for accessing session data in express?

There are numerous examples in node.js and express showcasing how to access session data. Exploring Node.js and Socket.io Express and Socket.io Integration Understanding Socket.io and Session Management Upon visiting the third link, which leads to Stac ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Is it possible for the children of a Three.js scene to have matrix positions that differ from the children of those children?

I am facing an issue with my ferris wheel. The baskets on the wheel are not aligning correctly when the scene is rotated: https://i.sstatic.net/Ek1mT.png Everything functions as intended until the scene is rotated, causing the baskets to misalign with th ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Generate a div dynamically and incorporate a function that triggers on click event dynamically

In my current project, I am faced with a challenge due to laziness. My goal is to automatically generate menu buttons that are linked to different sections of a page using raw JavaScript. The issue arises when the body content of my site is loaded from an ...

Execute javascript function upon user scrolling to a designated section in the webpage

Is there a method to trigger a unique function every time a user scrolls to a different div or section of the page? ...

Conceal the element if the output of express is void

I am currently developing an app using nodejs and express. I am retrieving JSON data from an endpoint and displaying it on the page based on the values received. The issue I am facing is that if I receive a null or undefined value from the JSON data, how ...

What is the reason behind Istanbul's code coverage reporting a switch statement as uncovered even though all conditional paths are covered?

Within my node.js application, there is a class that includes a getter method with a significant switch statement. Rather than the simple example provided below, this switch statement contains numerous unreleased product-specific values replacing 'a&a ...