How to chain a custom function to express-validator?

Issue

I am using express-validator and I have chained some validations to link parameter like this:

route.post('/landing-pages/:link/blocks',
[
    param('link').trim().escape().isString()
],
controller.addBlocks);

I need to add some chained functions like trim and escape to be able to modify the value.

I can use custom method like the following to add new validation:

route.post('/landing-pages/:link/blocks',
[
    param('link').trim().escape().isString().custom((value, { req, location, path }) => 
    {
            //return true/false based on custom validation.
    }
],
controller.addBlocks);

But instead of validating and returning true/false, I want to modify value and change it’s original source exactly the way that trim or escape is doing it. for example, I want to replace some characters or I want to remove some words, etc.

Is there anyway to do it with express-validator?

Solution

you can chain customSanitizer function for that purpose

param('link').trim().escape().isString().customSanitizer(value => {
    // imagine we have a sanitizer function
    const sanitizedLink = linkSanitizer(value)
    return sanitizedLink;
  })

Answered By – linusw

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published