Search code examples
javascriptnode.jsexpressexpress-validator

any ways to simplify Express-Validator middleware in seperate file


i have project that takes alot of validations using Express-Validator , so each time i need to validate something , i do like that in each file:

//Validation and Sanitizing Rules
const validationRules = [
  param('tab').isString().isLength({ min: 1, max: 8 }).trim().escape(),
  param('categoryID').isNumeric().trim().escape()
]
//Validate and get the result
const validate = (req, res, next) => {
  const errors = validationResult(req)
  // if every thing is good .. next()
  if (errors.isEmpty()) {
    return next()
  }
  //if something is wrong .. push error msg
  const extractedErrors = []
  errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
  return res.status(403).json({
    'status': 'alert error',
    'err': extractedErrors,
    msg: 'Any Error Msg Here:('
  })

i tried to create file validator.js then call it when ever i need it , but i didn't like the idea.

so im thiking about solution like custom wrapper for simplifying my validations in the future .. so i tried to create mine (custom wrapper) like that using letters keywords:

isString: 's',
isNumeric: 'n',
isLength: 'l',
trim: 'tr',
escape: 'es',
..etc

And now when i want to validate something like 'number' i pass it to my custom wrapper in an object :

customValidationRules({field : "categoryID", type: ['n','tr','es']})

and the validation in the wrapper will be :

param('categoryID').isNumeric().trim().escape()

any suggestion or guide line to follow to create this Kind of wrapper .. ty


Solution

  • You should flip it around, and use a structure like:

    const validators = {
        s: isString,
        n: isNumeric,
        ...
    };
    

    Then given a rule array validationRules like `['n', 'tr', 'es'], you can do:

    validationRules.reduce((rule, acc) => validators[rule].call(acc), param(paramName));