node.js - 如何在@hapi/joi 中设置自定义错误消息?
问题描述
我使用 Joi 创建了以下 Schema 进行验证:
const createProfileSchema = Joi.object().keys({
username: Joi.string()
.required()
.message("username is required")
.empty()
.message("username is not allowed to be empty")
.min(5)
.message("username must be greater than 5 characters")
.max(20)
.message("username must be less than 5 characters")
});
但它会引发流动错误:
Cannot apply rules to empty ruleset or the last rule added does not support rule properties
4 | username: Joi.string()
5 | .required()
> 6 | .message("username is required")
| ^
7 | .empty()
8 | .message("username is not allowed to be empty")
9 | .min(5)
实际上,我想为每个单独的错误案例设置一条自定义消息。
解决方案
您可以使用最新版本的 @hapi/joi 包尝试类似的操作。
const Joi = require("@hapi/joi");
const createProfileSchema = Joi.object().keys({
username: Joi.string()
.required()
.empty()
.min(5)
.max(20)
.messages({
"string.base": `"username" should be a type of 'text'`,
"string.empty": `"username" cannot be an empty field`,
"string.min": `"username" should have a minimum length of {#limit}`,
"string.max": `"username" should have a maximum length of {#limit}`,
"any.required": `"username" is a required field`
})
});
const validationResult = createProfileSchema.validate(
{ username: "" },
{ abortEarly: false }
);
console.log(validationResult.error);
详细信息可以在文档中找到:
https://github.com/hapijs/joi/blob/master/API.md#list-of-errors
推荐阅读
- c# - 使用c#创建文件夹的文件列表
- wordpress - 在 Docker 容器中托管 WordPress 网站的视频
- c# - VS2017 中带有 unicode 字符集的 C# 代码的编译错误
- python - django 模型 / mySQL 数据库中的 urandom
- javascript - 我们可以使用 axios 的 onDownloadProgress 来加载 API 吗?
- ios - 如何以编程方式更新 UITextView maximumNumberOfLines 并查看 UI 更新。
- java - 尽管它存在于 pom.xml 文件中,但我的项目没有看到特定的导入
- c# - 在 ftp 上发布 WinForm 并进行后续更新
- php - ZF3 你能记录未捕获的异常吗?
- mysql - MySQL - 如何根据两个不同表之间的关系从表中选择所有结果?