Node.js Joi 如何显示自定义错误消息?

新手上路,请多包涵

使用 Joi 验证用户在 Node.js RESTapi 中的输入似乎很简单。

但问题是我的应用程序不是用英文写的。这意味着我需要向前端用户发送自定义的书面消息。

我已经对此进行了谷歌搜索,但只发现了问题。

也许有人可以为此提供解决方案?

这是我用来验证 Joi 系统的代码:

     var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required(),
      lastName: Joi.string().min(5).max(10).required()
      ..
    });

    Joi.validate(req.body, schema, function(err, value) {
      if (err) {
        return catched(err.details);
      }
    });

    function catched(reject) {
      res.json({
        validData: false,
        errors: reject
      });
    }

另外,有没有办法在客户端使用 Joi

谢谢!

原文由 Raz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

我发现的一个解决方案是设置:

 var schema = Joi.object().keys({
  firstName: Joi.string().min(5).max(10).required().label("Your error message in here"),
  lastName: Joi.string().min(5).max(10).required()
  ..
});

然后从回调中打印 label error 变量

原文由 Raz 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是我在使用 joi 17.6 时如何做到的示例

VerifyAuthOtpValidator (otpProps: OtpProps) {
        const otpSchema = Joi.object<OtpProps>({
            otp_code: Joi.string().required().messages({
                "string.empty": "No OTP code provided",
                "any.required": "No OTP code provided",
            })
        });
        const {error, value} = otpSchema.validate(otpProps);
        //you can log the error property, as this would enable you
        // see the error type, which you can then, customise
        // the message
        // console.log("\n\t error: ", error)
        if(error){
            return error.message
        }
        return value
    }

原文由 Chukwunazaekpere 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题