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

Shi*_*ain 16 validation node.js 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")
});
Run Code Online (Sandbox Code Playgroud)

但它引发了流动错误:

 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)
Run Code Online (Sandbox Code Playgroud)

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

Sul*_*Sah 39

您可以使用最新版本的 @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);
Run Code Online (Sandbox Code Playgroud)

详细信息可以在文档中找到:

https://github.com/hapijs/joi/blob/master/API.md#list-of-errors


Sve*_*hig 5

你可以试试这个

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
});
Run Code Online (Sandbox Code Playgroud)