Home > Software engineering >  How to chain a custom function to express-validator?
How to chain a custom function to express-validator?

Time:08-31

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?

CodePudding user response:

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;
  })
  • Related