hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

allow() skipping all the validation in when() #2949

Open terrence-wong opened 1 year ago

terrence-wong commented 1 year ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

This is the schema I am working on. There are two fields: remarks and userList.

remarks can be optional(i.e. empty string or null) if userList is an empty array. If userList contains some elements, then remarks turns into a required field.

Joi.object({
  remarks: Joi.string().allow("", null),
  userList: Joi.array(),
}).when(
  Joi.object({
    userList: Joi.array().min(1),
  }).unknown(),
  {
    then: Joi.object({
      remarks: Joi.string().required(),
    }),
    otherwise: Joi.object({
      remarks: Joi.any(),
    }),
  }
);

This is the data I am trying to validate:

{ 
  remarks: '',
  userList: [{}]
 }
// OR
{ 
  remarks: null,
  userList: [{}]
 }

I tried in my project as well as the sandbox in the document page(https://joi.dev/tester/), and both doesn't work as expected. It seems if matches with allow(), then the then part will never check.

What was the result you got?

Validation Passed

What result did you expect?

Validation Error: "remarks" is not allowed to be empty