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?
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.
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.
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.
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.
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 }),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With