hapijs / joi

The most powerful data validation library for JS
Other
20.89k stars 1.51k forks source link

Custom transformation of a value #3030

Closed nicholaswmin closed 5 months ago

nicholaswmin commented 6 months ago

Runtime

node.js

Runtime version

v20

Module version

17.12.2

Used with

express-joi-validator

Any other relevant information

I wonder if it's possible to transform a validated value to a custom value.

For example, start is coming in as a String of a Unix timestamp but internally I use full dates, so I also need to cast it into a JS Date.

i.e some API like this would look nice:

start: Joi.date().timestamp('unix').required().transform(val => new Date(+val * 1000))

I basically want to avoid this convoluted bullcrap:

app.get('/datasets', validator.query(validator.schemas.datasets.get)), (req, res) => {
  req.query.start = new Date(+val)
  //... bla bla
})

Since I'm already declaring stuff about a parameter, the schema seems like a nice place to also transform/cast it.

nicholaswmin commented 6 months ago

Ah never mind, shoulda read the docs a bit more carefully next time:

Looks like .custom is good for this:

Joi.date().timestamp('unix').required().custom(val => new Date(+val * 1000))

The docs state:

any.custom(method, [description])

Adds a custom validation function to execute arbitrary code where:

I want to validate the input and then finally transform it for internal use. Is this the purpose of .custom or am I reading this incorrectly? That custom validation wording is a bit unclear since I'm only doing a transformation in my .custom. This has no impact on the validations, correct?

AdarshBajpai67 commented 5 months ago

hey @nicholaswmin , you're right .custom is described as "custom validation," and it's more versatile and can be used for both validation and data transformation

nicholaswmin commented 5 months ago

My $0.02: This should be clarified as such; transformation/validation are not interchangeable concepts.

Closing though.