首页 > 解决方案 > 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())

感谢您的时间

标签: node.jsexpressmiddlewareexpress-validator

解决方案


推荐阅读