hapijs / hapijs/joi

Custom error message for each validation step.

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

Description

#### Context

* *node version*: 16.4.0
* *module version*: 17.5.0
* *environment* (e.g. node, browser, native): node
* *used with* (e.g. hapi application, another framework, standalone, ...): nestjs
* *any other relevant information*:

#### How can we help?

Is there a better way to set custom error messages for each validation? Similar to Yup, is it possible to add custom messages in the validation function itself `.string().required('Custom required message')`. I can see the point to add all custom messages for the schema in a separate property where all messages can be accessed, but having this feature could be easy for understanding validations and their error messages.

```js
// Current implementation

const schema = Joi.object({
username: Joi.string()
.min(3)
.max(30)
.required()
.messages({
"string.min": "Must have at least 3 characters",
"string.min": "Must have max 30 characters",
"string.required": "This is required"
})
};

// Is something like this possible?

const schema = Joi.object({
username: Joi.string()
.min(3, (len) => `Must have at least ${len} characters.`))
.max(30, (len) => `Must have max ${len} characters.`))
.required("This is required")
};
```

The second option looks more readable and clear to me. Is there an option to achieve this?

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.