-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
joi errors not overriding for nested objects #1528
Comments
Duplicate of #1219. I know it's confusing but it's documented. |
Even applying code: const Joi = require('joi');
const schema = Joi.object().keys({
city: Joi.object().keys({
id: Joi.number().required().error(new Error('invalid city')),
}).required().error(new Error('city is required'))
});
console.log(schema.validate({ city: { id: 'asd' } }, { abortEarly: true }).error); // returns `city is required` instead of `invalid city` |
Seems no response so far, as a workaround, I wrote a helper function which gets labels instead and prints them (only first item in my case, no need multiple). P.S using const getProp = R.useWith(R.path, [R.split('.')]);
const maybeGetProp = R.curry((prop, obj) => F.Maybe(getProp(prop, obj)));
const maybeGetJoiError = R.pipeK(maybeGetProp('error.details'), x => F.Maybe(R.head(x)), maybeGetProp('context.key')); const userSchema = joi.object().keys({
city: joi.object().keys({
id: joi.number().required().label('invalid city'),
}).required().label('city is required')
});
const res = userSchema.validate({ city: {} }, { abortEarly: false });
maybeGetJoiError(res); // returns Maybe.Just({ value: 'invalid city' }) or Maybe.Nothing(). Let me know if it's correct approach for labels (e.g parsing correctly). Thanks. |
I think you missed the complexity of A working example would be: const schema = Joi.object().keys({
city: Joi.object().keys({
id: Joi.number().required().error(new Error('invalid city')),
}).required().error((errors) => {
// If at least one error comes from city itself
if (errors.some(e => e.context.key === 'city')) {
return new Error('city is required');
}
return errors;
})
}); |
Ahh.. Now it's all clear. Thank you! Closing this. |
Added a new syntax in 14.2.0 to support that more easily if you're interested. |
Can you provide a direct link to that new syntax? |
Context
What are you trying to achieve or the steps to reproduce ?
Which result you had ?
it returns 'city is required' unless all the nested objects are valid.
What did you expect ?
display error for each part.
while this works without .error(), I want to be able to send custom error messages for each part.
For example:
The text was updated successfully, but these errors were encountered: