hapijs / hapijs/joi

"label" local context defined in helper.error(code, opt) is override by the label of Messages.root.

Open
#2,950 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): no
* *is this issue affecting a production system?* (yes/no): yes

#### Context

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

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

I have a joi schema like

```js
const schema = joi.object({
id: joi.string()
usr: joi.string().min(3).max(10),
pwd: joi.string()
});
```

As id is assigned by db, I leave it optional. But later when I verify data come back from db. I want to check it is included in the data.
So, I defined a custom rule for this, which looks like

```js
schema.custom((val, helper) => {
if(val.id) return val;
return helper.error('any.required', {local: 'id', key: 'id'})
}, 'custom validation').validate({
usr: "test"
})
```

What I'm expecting is that an error reported for missing 'id'.

#### What was the result you got?

I actually get a validation error, but the message is `"value" is required`.
I checked the error details, `key` from local context is updated into `error.details.context`. But `label` is overridden by the root value.

#### What result did you expect?

The label defined in local context takes higher priority and shown in the error message. For the example case, the expecting message should `"id" is required`

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.