Skip to content

Joi wrong value parsing #964

@akaNightmare

Description

@akaNightmare

Context

  • node v6.2.0:
  • joi 9.0.0:
  • used with (expressjs):
const validator = Joi.object({
            name: Joi.string(),
            pricing_formula: Joi.string(),
            period: Joi.string().valid(Object.keys(this.model.PERIODS)).allow(null),
            is_active: Joi.boolean(),
            formula_variables: Joi.array().items(Joi.object({
                name: Joi.string(),
                type: Joi.string().valid(Object.keys(models.PricingFormulaVariable.TYPES)),
                value: Joi.alternatives().when('type', {
                    is: models.PricingFormulaVariable.TYPES.constant_map,
                    then: Joi.object({
                        default: Joi.number().integer().min(0)
                    }).required()/*.pattern(/[\w\d]+/, Joi.number().integer().min(0))*/,
                    otherwise: Joi.number().integer().min(0)
                }),
            })).unique((a, b) => a.name === b.name)
        }).options({
            allowUnknown: false,
            abortEarly: false,
            presence: 'required'
        });

const validatedBody = Joi.attempt({
                name: 'hello',
                pricing_formula: 'a + b + c',
                period: null,
                is_active: true,
                formula_variables: [
                    {
                        name: 'a',
                        type: 'variable',
                        value: 100
                    },
                    {
                        name: 'b',
                        type: 'constant',
                        value: 0
                    },
                    {
                        name: 'c',
                        type: 'constant_map',
                        value: '{}'
                    }
                ]
            }, validator);

Which result you had ?

Cannot create property '$miss$default|1$end$' on string '{}'

What did you expect ?

{  
   isJoi:true,
   name:"ValidationError",
   details:[  
      {  
         message:""         value" must be an object",
         path:"formula_variables.2.value",
         type:"object.base",
         context:{  
            key:"value"
         }
      }
   ],
   _object:{  
      name:"hello",
      pricing_formula:"a + b + c",
      period:null,
      is_active:true,
      formula_variables:[  
         {  
            name:"a",
            type:"variable",
            value:100
         },
         {  
            name:"b",
            type:"constant",
            value:0
         },
         {  
            name:"c",
            type:"constant_map",
            value:"{}"
         }
      ]
   }
}

Metadata

Metadata

Assignees

Labels

bugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions