There is this property you provide called stripUnknown that removes fields that were not specified during schema creation, is there something like but which removes invalid fields and returns the valid ones, maybe additionally with errors. Code sample
For example
var joi = require("@hapi/joi")
let s = joi.object({
name: joi.string(),
username: joi.string()
})
console.log(
s.validate({
name: 32,
age: 43
}, {
stripUnknown: true,
convert: true
})
)
Instead of it alerting the name is invalid only, it can return the value with name removed because it is invalid.
It is not an answer per se, as there is no specific function that supports removal of certain values (at least that I know of). I do not have the ability to comment yet, thus the answer post.
You can use Joi.custom in order to create a custom validator.
The custom accepts a callback(value,helper) and your code could be written as:
const schema = joi.object().custom((value, helper) => {
let validatedObject = {};
if (typeof value.name === 'string') {
validatedObject.name = value.name;
}
if (typeof value.username === 'string') {
validatedObject.username = value.username;
}
return validatedObject;
});
joi.attempt(params, schema, {stripUnknown: true});
This way you can return the value that you think is acceptable.
Also, you can use the helper object in order to retrieve various properties as the schema or the state of the current validation etc.
Hope I helped a bit
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