本文介绍了任何方法来简化单独文件中的Express-Validator中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Express-Validator 进行大量验证的项目,因此每次我需要验证某些内容时,我都会在每个文件中都这样做:

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:('
  })

我试图创建文件 validator.js ,然后在需要时调用它,但我不喜欢这个主意.

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

所以我想像 custom wrapper 这样的解决方案,以便将来简化我的验证..因此,我尝试使用字母关键字创建类似于我的(custom wrapper):

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']})

,包装中的验证将为:

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

创建此类包装程序的任何建议或指南.ty

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

推荐答案

您应该将其翻转,并使用类似以下的结构:

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

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

然后给定规则数组 validationRules 之类的'['n','tr','es'],您可以执行以下操作:

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

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

这篇关于任何方法来简化单独文件中的Express-Validator中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 15:18