13

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?

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
Alexander
  • 161
  • 1
  • 1
  • 4

5 Answers5

19

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.

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
  • Your solution validates a float within a certain range, but the question is to validate an integer or a float within a certain range. – Reinier Garcia May 09 '23 at 22:07
5

for int check

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

Rafiq
  • 8,987
  • 4
  • 35
  • 35
  • 1
    Your solution validates an integer within a certain range but the question is to validate an integer or a float within a certain range. – Reinier Garcia May 09 '23 at 22:09
0

SOLUTION

It validates numbers in general, exactly as requested ("an integer or a float within a certain range")

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"),
Reinier Garcia
  • 1,002
  • 1
  • 11
  • 19
-1

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.

Dan
  • 2,455
  • 3
  • 19
  • 53
-1

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

enter image description here