Search code examples
node.jsjoihapi

Joi validation on payload where value name has a hyphen


As it says in the title i cant get the joi validation to work on a value in my payload with a hypen in its name. The value is called 'search-type'. My validation looks like this

  options: {
    validate: {
      payload: joi.object({
        value1: joi.string().required(),
        value2: joi.string().required(),
        search-type: joi.string().required()
      }),
      failAction: (request, h, err) => {
        return h.redirect('/search').takeover()
      }
    }
  }

Ive tried putting the name in square brackets like this

 options: {
   validate: {
     payload: joi.object({
       value1: joi.string().required(),
       value2: joi.string().required(),
       searchType:['search-type'] joi.string().required()
     }),
     failAction: (request, h, err) => {
       return h.redirect('/search').takeover()
     }
   }
 }

but the 'joi.' after it flags up in linting and says 'joi.' is an unexpected token?


Solution

  • Use

     options: {
       validate: {
         payload: joi.object({
           value1: joi.string().required(),
           value2: joi.string().required(),
           'search-type': joi.string().required()
         }),
         failAction: (request, h, err) => {
           return h.redirect('/search').takeover()
         }
       }
     }
    

    Since this is Joi I am guessing you don't need to access that property anywhere else, but you would do that with options.validate['search-type'] and not options.validate.search-type as the - would be interpreted as the subtraction operator.