I need to get the key from the context, I expected context.key to be the key, but it turns out it's the label.
const Joi = require("joi");
const context = Joi
.object({
someKey: Joi.required().label("some label")
})
.validate({})
.error.details[0].context;
console.log(context);
{
key: "some label"
}
{
key: "someKey"
}
This example on RunKit: https://runkit.com/57d675ee7580c314003cf648/58fe1d4fad401b00120f475a/branches/master
Honestly not trying to be snarky here, but I mean.. that's kind of the point of .label() though isn't it?
https://github.com/hapijs/joi/blob/master/API.md#anylabelname
Overrides the key name in error messages.
@WesTyler I'm trying to convert Joi errors to something like
{
"name": "\"Name\" is required",
"phone": "\"Phone\" is required"
}
in order to display them in my HTML forms that have inputs with names:
<input name="name">
<input name="phone">
How do you suggest I do that if Joi errors give me only labels that are different for every language?
{
"袠屑褟": "<translated message>",
"孝械谢械褎芯薪": "<translated message>"
}
I noticed this a while ago and waited for someone to complain about it :)
This is a breaking change though, so it'll have to wait for next major.
@Marsup What's the change? It looks like it is working as described in the docs, so is the "fix" to change the behavior altogether?
The key should remain the json key, just as path is not affected by the label. There should probably be one more property added to the details.
@Marsup Fixing a bug is not a breaking change, it's a fixing change.
Users that rely on buggy behavior should blame themselves and fix their code.
That makes sense :+1:
Also, just realized I was conflating "override key name in error messages" with "override key name in context details"... Sorry mates haha.
Good luck patching joi without making it a breaking change, unless you choose the dirty path of making key = alias || key and some other thing represent the original key.
Most helpful comment
The
keyshould remain the json key, just aspathis not affected by the label. There should probably be one more property added to the details.