hapijs / joi

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

Is it possible to transform the output data after schema validation? #2924

Closed meircarlos closed 1 year ago

meircarlos commented 1 year ago

I would like to have a schema that after being validated with the validate function it transforms the output data to a new format.

For instance:

const schema = Joi.object({
    name: customJoi.string(),
    email: customJoi.string().email().required(),
}).transform((value) => {
    if (value.name === "John") value.name = "Jonathan";
    return value;
});

const data = {
    name: "John", email: 'jane@example.com'
};
const result = schema.validate(data);

// result.name should be "Jonathan"

If possible, I would also love that the transform function could be asynchronous and that it could even return a different type. As, let's say I could maybe want to return the object stringified.

Marsup commented 1 year ago

You can use https://joi.dev/api/?v=17.8.3#anyexternalmethod-description for this, but you'll have to use validateAsync.

See https://runkit.com/embed/av457l3cbbk2

meircarlos commented 1 year ago

This is great! Thanks for your help Marsup :D