【问题标题】:Node Js Express validator Check if field is numeric only if it is not emptyNode Js Express验证器仅在字段不为空时检查字段是否为数字
【发布时间】:2020-10-28 18:12:54
【问题描述】:

我使用 express-validator 来检查我的帖子字段,我的字段之一必须是小数或空。我使用了这个架构:

request.checkBody({ 
        'product_price': {
            optional: true,
            isDecimal: {
                errorMessage: 'The product price must be a decimal'
            }
        }
})

此架构的问题是如果 product_price 为空,即使使用“可选:true”,也无法验证我的帖子。

【问题讨论】:

  • 第一件事。 optional: true, // won't validate if field is empty。但从您的问题来看,您似乎假设相反是正确的,也许是错字?
  • 你试过notEmpty: true吗?这都是直接来自readme,如果我重复明显的事情,请见谅。
  • 其实用这个Schema,如果product_price为空,表单是不验证的;女巫不是我的需要。我希望它仅在不为空时才被检查(是否为十进制)。你能开发出什么是错字吗??
  • 这个场景需要:product_price : '' //validation OK product_price: 25.25 //validation OK product_price: 'ABC' //validation NOK
  • @ippi 也许我误解了这个问题。我改了标题

标签: node.js express


【解决方案1】:

您需要为optional 设置checkFalsy 选项以允许定义但为空的值:

request.checkBody({ 
  'product_price': {
    optional: {
      options: { checkFalsy: true }
    },
    isDecimal: {
      errorMessage: 'The product price must be a decimal'
    }
  }
});

编辑:自发布此答案以来,文档已被移动,现在可以找到 here

【讨论】:

  • 这正是我需要的,谢谢。
【解决方案2】:

对我有用的是使用req.checkBody('optionalParam', 'optionalParam must be a number').optional().isNumber();

【讨论】:

    【解决方案3】:

    如果有人使用express-validator body。您可以执行以下操作

    router.post('apiname', [
      body('product_price').trim()
        .optional({ checkFalsy: true })
        .isNumeric().withMessage('Only Decimals allowed'),
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多