Description
Runtime
node.js
Runtime version
20.18.0
Module version
17.13.3
Last module version without issue
No response
Used with
standalone
Any other relevant information
When using Joi's min(1)
validation on an object that also contains required fields, the min(1)
error message is never displayed because required field validation takes precedence.
What are you trying to achieve or the steps to reproduce?
- Create a schema with a nested object that has both
min(1)
constraint and required fields inside it - Set custom error messages for both the
min(1)
constraint and the required fields - Validate an empty object against this schema
- The required field error always shows instead of the
min(1)
error
import { describe, expect, it } from "@jest/globals";
import Joi from "joi";
const objectSchema = Joi.object({
user: Joi.object({
gender: Joi.string()
.required()
.empty(false)
.valid("male", "female")
.messages({
"any.required": "gender is required",
"any.only": "gender is not an allowed value",
"string.base": "gender is not a string",
"string.empty": "gender cannot be empty",
}),
})
.required()
.min(1)
.unknown(false)
.messages({
"any.required": "user is required",
"object.base": "user is not an object",
"object.min": "user cannot be empty",
"object.unknown": "user cannot contain unknown fields",
}),
});
describe("min(1) validation message not triggered when object has required fields", function () {
it("should throw when user is an empty object", function () {
const { error } = objectSchema.validate({
user: {},
});
expect(error.message).toBe("user cannot be empty");
});
});
What was the result you got?
When validating an empty user object ({user: {}}), Joi returns the error message "gender is required" instead of "user cannot be empty", even though I've explicitly set a custom message for the min(1) constraint. The validation prioritizes the required field validation over the min(1) validation, making it impossible to use the min(1) error message when required fields are present.
What result did you expect?
I expected Joi to respect the min(1) constraint and return the error message "user cannot be empty" when validating an empty user object. I want to be able to customize which validation takes precedence, or at least have the ability to show the more general "object is empty" message before showing individual field requirements.