Skip to content
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

How can I define both specific error messages and a default error message? #2708

Closed
ViniciusFH opened this issue Nov 27, 2021 · 0 comments
Closed
Assignees
Labels
feature New functionality or improvement
Milestone

Comments

@ViniciusFH
Copy link

Support plan

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

Context

  • node version: 14.17.4
  • module version: 17.4.2
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): express
  • any other relevant information:

How can we help?

So, there's this option to define custom messages for specific errors in validations, as in:

const schema = Joi.object().keys({

    prop: Joi.string().required(),

}).messages({
    'any.required': 'All fields must be filled',
});

So when "prop" is not defined in the object under validation, I receive an error message All fields must be filled, because that's what I defined for any.required errors. Any other errors, like prop not being a string, will have the error messages previously defined by Joi, for instance "prop" must be a string.

What I'd like to do is to define a custom message for those other validation errors, that will apply for any case except the ones that I have explicitly defined. Something like:

const schema = Joi.object().keys({

    prop: Joi.string().required(),

}).messages({
    'any.required': 'All fields must be filled',
    'anyOtherError': 'Custom message for any other error',
});

If .required() validation fails, I should get All fields must be filled, and in any other error case, I should get Custom message for any other error.

Is this possible? How do I do that?

@hueniverse hueniverse self-assigned this Dec 1, 2021
@hueniverse hueniverse added the feature New functionality or improvement label Dec 1, 2021
@hueniverse hueniverse added this to the 17.4.4 milestone Dec 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New functionality or improvement
Projects
None yet
Development

No branches or pull requests

2 participants