Joi Validation : Conditionally validate one key based on the value of another key

119
July 24, 2019, at 5:10 PM

I am trying to Joi validate one key depending on the value of another key.In the following example ,I have tried to validate category_children based on has_sub_category's value.has_sub_category may be true or false .When it is false, category_children should be empty array.If its true,it should not be empty.

category_children: Joi.when('category_has_sub_category',
            {is: false,
            then: Joi.array().max(0),
            otherwise: Joi.array().items(Joi.objectId()).min(1)}),
category_has_sub_category: Joi.boolean(),

But the above code doesnt seem to work.It gets validated when has_sub_ category is false and category_children is not empty and vice versa

Answer 1

You are very close, you just need to use any.allow(...values) in order to allow an empty array.

So change this

 then: Joi.array().max(0)

to this

 then: Joi.array().max(0).allow([])
READ ALSO
Problems with fetching div's ID

Problems with fetching div's ID

I have a problem with getting the div's ID from my applicationI have a JSP file, which generates a HTML

17
How can I change code background color when using nbconvert?

How can I change code background color when using nbconvert?

When converting Jupyter Notebook to html I am trying to change code background color using a Jinja template

12
scroll to bottom not working chatwindow ionic

scroll to bottom not working chatwindow ionic

I have a chat page in my app where the chat-div is inside a wrapper-divThe structure looks like this:

18
index.js:12 Uncaught TypeError: Cannot read property 'remove' of undefined at nextSlide

index.js:12 Uncaught TypeError: Cannot read property 'remove' of undefined at nextSlide

What I'm trying to get is the responsive image slider like carousel type in bootstrap with the help of JS however I'm getting the following error when I click on the next arrow button

115