node.js - 如何在@hapi/joi中设置自定义错误消息?

标签 node.js validation express joi

我使用 Joi 创建了以下用于验证的架构:

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

关于node.js - 如何在@hapi/joi中设置自定义错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58408362/

相关文章:

javascript - 如何正确地将 react 导入到 node-webkit 应用程序中?

node.js - 502 错误网关,docker 内有 nginx 和 Node

excel - 将列表验证添加到除前两行之外的列

PHP CodeIgniter 框架中的 Javascript 可用性验证

node.js - 修改 Node.js req 对象参数

node.js - MongoDB全文搜索和按相关性排序的多个单词

javascript - 在 React 中找不到所需的模块

php - Laravel Validator 规则中不同字段上的多个 "required_if"

javascript - 如何阻止 “GET” 被记录

javascript - 从 JavaScript 在 ExpressJS 中设置 View 变量