Joi: How to remove a key from joi

Created on 20 Dec 2017  路  6Comments  路  Source: sideway/joi

Context

  • node version: v9.2.0
  • joi version: 6.10.1
  • environment (node, browser): ubuntu
  • used with (hapi, standalone, ...): standalone
  • any other relevant information:

What are you trying to achieve or the steps to reproduce ?

  1. My schema is in #1380 it is on POST method.
  2. Now I want to remove a key in PATACH and PUT method.
  3. How can I achieve that goals
    for example
module.exports = function(req, res, next) {

  /**
   * If method is PATCH and PUT
   * then edit email and confirmEmail
   * and remove password and confirmPassword
   */
  if(req.method === 'PATCH' || req.method === 'PUT') {
     // how ?
  }
  let data = req.body;
  let err = Joi.validate(data, schema, {abortEarly: false});
  if (err && err.error !== null) {
    unique= [];
    message =[];
    err.error.details.forEach(element => {
      if(!(element.path in unique )) {
        unique[element.path]=1;
        message.push(element);
      }
    });
    res.status(422).json({message: message});
    res.end();
    return false;
  }
  next();
}

Which result you had ?

What did you expect ?

I tried so many ways but did not find the solution for example,

if(req.method === 'PATCH' || req.method === 'PUT') {

      schema['email'] =   Joi.string().optional().email();
      schema['confirmEmail'] = Joi.any().valid(Joi.ref('email')).optional().options({ language: { any: { allowOnly: 'does not match with email' } } });
      delete schema['password'];
      delete schema ['confirmPassword'];
      delete schema ['userType'];

  }
non issue support

All 6 comments

The thing is that I wanna remove before validation. beside I want to edit some key. For example, email field is required on post method, but I want to make it optional on PATCH and PUT method.

const schemaForPost = Joi.object({
   email: Joi.string().required(),
   someotherthing: Joi.string()
});

now .required be removed/overriden from email in subsequent schema
by concatenating like this:

const schemaForPut = schemaForPost.concat(
    Joi.object({ 
        email: Joi.string().optional(),
        someotherthing: Joi.string()
    })
);

that said its probably best to just define 2 different schemas....

I separate my schema for edit, thanks

a method like .without() but that work inverse
or a method like .strip() but that works BEFORE validation, would be great!

i mean something like:

const schema = Joi.object().keys({
    a: Joi.any(),
    b: Joi.any(),
   c: Joi.any(),
}).withOnly('a', 'c');

//resulting in a schema with only a and c
const stripped = Joi.object().keys({
    a: Joi.any(),
    c: Joi.any(),
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Dreamystify picture Dreamystify  路  4Comments

mohamadresaaa picture mohamadresaaa  路  3Comments

leore picture leore  路  4Comments

normancarcamo picture normancarcamo  路  3Comments

REBELinBLUE picture REBELinBLUE  路  3Comments