hapijs / hapijs/joi

min(1) validation message not triggered when object has required fields

Open
#3,069 1 comment 0 reactions 0 assignees View on GitHub
bug
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

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?

1. Create a schema with a nested object that has both `min(1)` constraint and required fields inside it
2. Set custom error messages for both the `min(1)` constraint and the required fields
3. Validate an empty object against this schema
4. 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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.