hapijs / hapijs/joi

allow() skipping all the validation in when()

Open
#2,949 0 comments 0 reactions 0 assignees View on GitHub
support
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

#### Support plan

* *is this issue currently blocking your project?* (yes/no): yes
* *is this issue affecting a production system?* (yes/no): no

#### Context

* *node version*: any
* *module version with issue*: v17.9.1
* *last module version without issue*:
* *environment* (e.g. node, browser, native): browser
* *used with* (e.g. hapi application, another framework, standalone, ...):
* *any other relevant information*:

#### 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.

```js
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:
```js
{
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
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.