Validate input is within a numeric range, possibly a float, using express-validator

Viewed 13221

I'm trying to validate if the input is an integer or a float within a certain range using express-validator. I've tried:

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

but the min and max values don't actually work. I tried putting in numbers above 5 and they don't throw an error.

The code below works, it won't allow numbers outside of the min and max limits:

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

but only for integer numbers, not for decimals, and the input needs to be either a decimal or an integer number between 0 and 5.

Is there a way to do this?

4 Answers

isNumeric doesn't have a min and max values, you can use isFloat instead:

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

You can read more about those methods in validator.js docs.

for int check

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

isNumeric and isFloat doesn't have a min and max values, you can use not() instead:

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

but only for integer numbers, not for decimals, and the input needs to be either a decimal or an integer number between 1000 and 4000.

Thank you.

I use .isInt() .isNumeric() donot work but .isFloat() work for me

enter image description here

Related