NodeJS 使用express-validator验证输入是否在数值范围内,可能是浮点数

a0zr77ik  于 2023-05-17  发布在  Node.js
关注(0)|答案(5)|浏览(137)

我尝试使用express-validator验证输入是整数还是一定范围内的浮点数。我试过了

check(
      'rating',
      'Rating must be a number between 0 and 5'
).isNumeric({ min: 0, max: 5 }),

minmax值实际上不起作用。我试着输入大于5的数字,它们不会抛出错误。
下面的代码可以工作,它不允许minmax限制之外的数字:

check(
      'rating',
      'Rating must be a number between 0 and 5'
).isInt({ min: 0, max: 5 })

但仅适用于整数,不适用于小数,并且输入需要是小数或05之间的整数。
有办法做到这一点吗?

nwlls2ji

nwlls2ji1#

isNumeric没有minmax值,您可以使用isFloat代替:

check('rating', 'Rating must be a number between 0 and 5')
  .isFloat({ min: 5, max: 5 })

你可以在validator.js文档中阅读更多关于这些方法的内容。

7fhtutme

7fhtutme2#

for int检查

body('status', 'status value must be between 0 to 2')
      .isInt({ min: 0, max: 2 }),
iswrvxsc

iswrvxsc3#

isNumeric和isFloat没有最小值和最大值,你可以使用not()来代替:

body("dialyPrice", "Daily price must be between 1000 to 5000").not().isNumeric({ min: 1000, max: 4000 }),

但仅用于整数而不用于小数,并且输入需要是小数或1000和4000之间的整数。
谢谢大家。

6yt4nkrj

6yt4nkrj4#

我使用.isInt().isNumeric()不工作,但.isFloat()为我工作

uidvcgyl

uidvcgyl5#

解决方案

它验证一般的数字,完全按照要求(“* 某个范围内的整数或浮点数 *”)

body('rating')
    .exists({checkFalsy: true}).withMessage('You must type a rating')
    .custom((value, {req, location, path}) => {
        const {body: {rating}} = req;
        const ratingFloat = rating.toFixed(2);
        return ratingFloat >= 0 && ratingFloat <= 5
    }).withMessage("You must type a rating lower or equal than 5 & bigger or equal than 0"),

相关问题