-
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
Custom error for each validation option? #1739
Comments
This is because you are not applying a custom error to each individual option, you are applying 3 sequential errors to the same single property. The following is the same end result as your code, but makes the calls more clear: Joi.string()
.min(5)
.max(25)
.required()
.error(() => 'first message')
.error(() => 'second message')
.error(() => 'third message') |
One option you can leverage is the callback function in Joi.string()
.min(5)
.max(25)
.required()
.error((errors) => {
// if abortEarly === false,
// errors contains the details for all options that failed
// if abortEarly === true,
// errors contains the details for the first option that failed
}) |
@WesTyler, thanks for the explanation! For my situation I just found such solution: const schema = Joi.object().keys({
title: Joi.string()
.min(minLength)
.max(maxLength)
.required()
.error((errors) => {
return errors.map(error => {
switch (error.type) {
case "string.min":
return { message: "first msg" };
case "string.max":
return { message: "second msg" };
case "any.empty":
return { message: "third msg" };
}
}
)
}) Seems not the best one, as it cause too many code, especialy if you have big form, hovewer it works as I desire. If they're not a more convenient solution for my case, an issue can be closed. Thanks again for your help! |
I think that's going to be your best bet for what you're trying to do. Glad it worked! |
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions. |
I have
Joi
schema and want to specify a custom error message for each of the options.Example of my schema:
At the moment this validation works in such way: if whatever of the option is invalid only third message appears.
Expected behavior - error message appears according to which option is invalid (as default Joi behavior, but with my custom error message).
Thanks in regards!
The text was updated successfully, but these errors were encountered: