neil
neil

Reputation: 169

How to validate decimal numbers precision using Joi

I am validating the request body for one of the API I am working on to insert the data in the DB. DB has precision as 3.

Using Joi, I am validating as

f_num: Joi.number().precision(3).required()

My understanding was that it'll only allow decimal precision upto 3 and should throw an error if there's a number like 1.345678 saying the precision should be 3.

But it goes through and while inserting the data , it rounds to 3 decimal places in the database.

Is there a way to check the exact precision using Joi? I tried searching online but not able to find any answers.

Upvotes: 1

Views: 3254

Answers (2)

Harkness
Harkness

Reputation: 31

If you don't want to disabled convert globally you can just use

f_num: Joi.number().precision(3).prefs({ convert: false }).required() 

source: https://joi.dev/api/?v=17.9.1#anyprefsoptions---aliases-preferences-options

Upvotes: 1

salah-chaouch
salah-chaouch

Reputation: 101

Using precision will by default just round the decimals to the specified maximum. If you want it to fail the validation instead, set convert to false as per the documentation:

joi.validate(objectToValidate, schema, {convert:false});

Upvotes: 1

Related Questions