Joi: idea: Strip if condition is true

Created on 6 Jan 2017  路  8Comments  路  Source: sideway/joi

Context

Would be great if you could pass condition and it would strip the value

lets say I would like to strip all null and undefined value I could use _.pickBy(request.payload)

payload: Joi.object({
    name: Joi.string().optional().stripIf(['null','undefined']),
    age: Joi.number().optional().stripIf(['null', 'undefined',0]),
    zip: Joi.number().optional().allow(null),
})

than request.payload should be equal to:

{ zip: 12345 }
feature

Most helpful comment

undefined is not possible in JSON, the other values can already be dealt with by a workaround :

payload: Joi.object({
    name: [Joi.only(null).strip(), Joi.string()],
    age: [Joi.only([null, 0]).strip(), Joi.number()],
    zip: Joi.number().allow(null),
})

Good enough ?

All 8 comments

undefined is not possible in JSON, the other values can already be dealt with by a workaround :

payload: Joi.object({
    name: [Joi.only(null).strip(), Joi.string()],
    age: [Joi.only([null, 0]).strip(), Joi.number()],
    zip: Joi.number().allow(null),
})

Good enough ?

Thanks a lot! @marsup

I used to use this pattern alot in Joi 14

[Joi.only(null).strip(), Joi.string()],

however in Joi 16 seems like it is not working. it throws error Invalid mode: null

That's documented in the release notes, you should read it before migrating.

@Marsup no one read release notes :)

Countless hours and efforts are put into those, RTFM is the best answer I can give at some point :man_shrugging:

This is the syntax that worked with me:
[Joi.string(), Joi.strip()],

I reckon it was much easier to share that instead of assuming that I did not read the docs. Simply I read the docs and it was not mentioned there what is the new syntax that should work Joi 16
Thanks anyway.

@menocomp the new syntax you should use

Joi.object({
  a : Joi.alternatives().try(
      Joi.string(),
      Joi.any().strip()
  )
})

you can test it here: https://hapi.dev/family/joi/tester/

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mohamadresaaa picture mohamadresaaa  路  3Comments

alekbarszczewski picture alekbarszczewski  路  3Comments

PaunPrashant picture PaunPrashant  路  3Comments

normancarcamo picture normancarcamo  路  3Comments

JbIPS picture JbIPS  路  4Comments