Express Validator - 根据参数值有条件地使字段成为必需

时间:2021-03-11 11:52:59

标签: node.js express middleware express-validator

我在将以下验证链合二为一时遇到问题。当然,这不是一个大问题,但我想知道如何解决。

仅当名为 type 的变量的值为“FINAL”时才需要字段文档,否则它应该是可选的且可为空的。

我想优化的工作解决方案:

body('documents')
  .isArray()
  .optional({ nullable: true })
  .withMessage('documents should be an array'),

body('documents')
  .if(body('type').equals('FINAL'))
  .isArray()
  .withMessage('documents should be an array'), 

我认为可行的方法:

body('documents')
  .isArray()
  .if(body('type').not().equals('FINAL'))
  .optional({ nullable: true })
  .withMessage('documents should be an array'),

也试过.if(body('type').equals('FINAL').not())

感谢您的时间

0 个答案:

没有答案