hapijs / hapijs/joi

Using `.when` to check 2 values

Open
#3,041 1 comment 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

### Runtime

Node.js

### Runtime version

v20.4

### Module version

17

### Used with

standalone

### Any other relevant information

_No response_

### How can we help?

Hi, struggling to figure out how I can apply a `then` clause based on whether one key has a certain value or another key has a different value, hoping somebody could help...

I currently have something like this:

```javascript
.when("foo", {
is: "bar",
then: object.keys({
somethingElse: string.optional().allow()
})
});
```

And I'd like to extend it so that if either `foo="bar"` OR `baz="qux"` will both apply the `then`. I know I could† add another `.when` and move my `then` stuff into a var, or duplicate it (actual code has a lot of conditions though so want to avoid any duplication) like this:

```javascript
const overrides = object.keys({ somethingElse: string.optional().allow("") });

/* ...snip... */
.when("foo", { is: "bar", then: overrides })
.when("baz", { is: "qux", then: overrides })
```
but it feels like there must be a cleaner way to do it? Maybe with `alternatives` or something?

Thank you :pray:

† I'm assuming this would work anyway, haven't actually tried it

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.