Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript NodeJS Joi validation for large numbers

I am creating an application in NodeJS 12 using the Joi validation library to validate the API request body.

I am having an issue with number data types that are more than 16 digits long.

I want to validate a number that is 18 digits long.

The validation works for smaller numbers but it does not work for larger numbers. I think this might be due to a limitation with the size of numbers.

I am not able to follow the selected answer in this similar question because the field cannot be converted to a string. It must be processed and stored as a number in the database.

Example value:

999830129121239112

Joi validation rule

ExampleNumber: Joi.number().integer().max(999999999999999999).allow(null),

Error message:

{"message":"'ExampleNumber' must be a safe number at body,ExampleNumber","field":"ExampleNumber"}
like image 605
pengz Avatar asked Jul 23 '19 18:07

pengz


1 Answers

You need to use number.unsafe() to validate large numbers,

From the API doc:

const safeNumber = Joi.number();
safeNumber.validate(90071992547409924);
// error -> "value" must be a safe number

const unsafeNumber = Joi.number().unsafe();
unsafeNumber.validate(90071992547409924);
// error -> null
// value -> 90071992547409920
like image 192
Aritra Chakraborty Avatar answered Sep 21 '22 15:09

Aritra Chakraborty