【问题标题】:How to set custom error messages in @hapi/joi?如何在@hapi/joi 中设置自定义错误消息?
【发布时间】:2020-02-12 22:37:34
【问题描述】:

我已经创建了以下 Schema 用于使用 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)

实际上,我想为每个单独的错误案例设置一条自定义消息。

【问题讨论】:

标签: node.js validation express joi


【解决方案1】:

您可以使用最新版本的 @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

【讨论】:

  • 你能解释一下你为什么通过这个{ abortEarly: false }
  • @ShifutHossain abortEarly options 默认值为 true,当为 true 时会导致返回第一个错误,因此如果要获取模型中的所有错误,必须将其设置为 false,这里只有一个字段(用户名),所以它没有区别。
  • 并且在文档中说:当为真时,停止对第一个错误的验证,否则返回找到的所有错误。默认为真。
  • 如果我想针对任何情况返回一条错误消息怎么办?
【解决方案2】:

你可以试试这个

const Joi = require("@hapi/joi"); // as of v16.1.8

const createProfileSchema = Joi.object().keys({
  username: Joi.string()
    .required()
    .empty()
    .min(5)
    .max(20)
    .error(errors=>{ 
     errors.forEach(err=>{  
     switch(err.code){
         case "string.empty":
         err.message='Please insert username'
         break

         case "string.max":
         err.message='username is not allowed to be empty'
         break
        }
      })
    return errors
});

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2018-07-21
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多