joihapi

check if an input variable is string or array using joi


I have an api that in the past developments would receive comma separated strings as valid input and used the following as the validator: Joi.string()

But now I want to implement the same variable using array of strings as mentioned here https://github.com/glennjones/hapi-swagger/issues/119. So the new check would be:

Joi.array().items(Joi.string())

But I do not want to break the backward compatibility of the code. Is there a way to check both conditions for the variable?

I am a newbie to Joi, so any help or guidance would be appreciated. Thanks in advance.


Solution

  • Take a look at .alternatives().try() which supports multiple schemas for a single field.

    For example:

    Joi.alternatives().try(Joi.array().items(Joi.string()), Joi.string())
    

    This will validate both arrays of strings and plain strings, however as I'm sure you know, you'll still need server side logic to check which format the value is so you can process it properly.