Search code examples
node.jsexpressexpress-validator

How to chain express-validator based on query values?


I am trying to find a solution to chain conditions based on the query values passed to the route.

Task1:
// if value for query A = noIdNeeeded, then i do not need to search for a second queryB
/endpoint?queryA=noIdNeeded

Task2:
// if value for query A = idNeeded, then i need to ensure second queryB exists
/endpoint?queryA=idNeeded&queryB=SomeId

I am having trouble with the writing parameter for Task 2.

For task 1 i have use this logic and works fine [query('page').exists().notEmpty().isIn(seoPageTypes),]

So far I have seen there is an if clause that we can use probably (link) however implementing this has been a challenge due to lack of examples and no prior experience.

If anyone can guide on how to do this correctly or any hint is much appreciated.


Solution

  • Make sure you have a new version of express-validator installed.

    The following should do your job.

    query('queryA').exists().notEmpty().isIn(seoPageTypes),
    query('queryB')
        .if(query('queryA').equals('idNeeded'))
        .exists().notEmpty().withMessage('queryB must exist'),
    

    Another approach is to use a custom validator

    query('queryA').exists().notEmpty().isIn(seoPageTypes)
        .custom((value, {req}) => {
            if (value === "idNeeded" && !req.query.queryB) {
                throw new Error('queryB must exist');
            }
            return true;
        }),
    

    Use what suits you more :)