Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if an input variable is string or array using joi

Tags:

joi

hapi

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.

like image 436
Jasjeet Kaur Avatar asked May 10 '26 08:05

Jasjeet Kaur


1 Answers

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.

like image 89
Ankh Avatar answered May 13 '26 21:05

Ankh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!