Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove invalid fields during Joi Schema Data Validation instead of returning an error?

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.

like image 633
Nehemie Niyomahoro Avatar asked Dec 18 '25 09:12

Nehemie Niyomahoro


1 Answers

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

like image 71
konkasidiaris Avatar answered Dec 19 '25 23:12

konkasidiaris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!