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

时间:2019-10-16 07:53:04

标签: 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)

实际上,我想为每个错误案例设置自定义消息

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以尝试

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
});