Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 268
Alexander Avatar asked Aug 13 '20 22:08

Alexander


People also ask

How do I validate an input field in express?

Validate input by validateInputField: check (input field name) and chain on the validation isDate () with ‘ . ‘ Use the validation name (validateInputField) in the routes as a middleware as an array of validations. Destructure ‘validationResult’ function from express-validator to use it to find any errors.

How to validate input fields to accept only float numbers?

In a certain input field, only float numbers are allowed i.e. there not allowed any strings, special characters or anything other than float or a number which capable of convert to float by itself (ex- int). We can also validate these input fields to accept only float numbers using express-validator middleware. Install express-validator middleware.

What are the different types of validation in HTML forms?

In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only a valid date is allowed i.e. there is not allowed any strings, number, or invalid date characters.

How do I create a validator in JS?

Create a validator.js file to code all the validation logic. Validate input by validateInputField: check (input field name) and chain on the validation isDate () with ‘ . ‘ Use the validation name (validateInputField) in the routes as a middleware as an array of validations.


2 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.

like image 81
Shahriar enayaty Avatar answered Nov 17 '22 02:11

Shahriar enayaty


for int check

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

like image 34
Lord Avatar answered Nov 17 '22 02:11

Lord