繁体   English   中英

Joi验证:捕获自定义错误消息中传递的值

[英]Joi Validations: Capture the value passed in Custom Error Message

我正在使用带有NodeJs / Typescript的Joi库进行验证。 验证请求主体以进行后期操作。

我正在使用语言选项来为各个字段验证提供自定义消息。

下面是代码

const bodySchema = Joi.object().keys({
    // had to change from string to any so as to avoid multiple messages when empty
    field1: Joi.any().required().valid('Dummy').options({
        language: {
            any: {
                // wrt empty: specific error  message not displaying  with any but empty error is handled by allowOnly custom message. Anways there is no custom message for empty in requirements
                // empty: '!!The parameter \'field1\' cannot be empty. It must be \'Dummy\'',
                required: '!!The parameter \'field1\' is mandatory and must be the value \'Dummy\'',
                allowOnly: '!!Invalid value for parameter \'field1\'. It must be \'Dummy\''
            // how to capture value passed for field1 in the message?
            }
        }
    }),

如何捕获在自定义错误消息中作为requestBody传递的错误字段值

例如,如果我传递POST端点的请求正文

 {
  "field1": "wrongvalue",
 }    

预期的自定义消息参数\\'field1 \\'的无效值'wrongvalue'。 它必须是\\'Dummy \\'

我已经通过JOI API,但是找不到任何参考。 正则表达式选项具有捕获传递的值的功能。 {{value}}适用于正则表达式,但不适用于其他选项。

请让我知道是否有一种获取价值的方法。

尝试这个 ......

const typeSchema = Joi.object({field1: Joi
    any()
    .required()
    .valid('Dummy')            
    .error(errors => {
      errors.forEach(err => {
        switch (err.type) {
          case "string.base":
          case "required":
            err.message = "field 1 is mandatory and must be the value";
            break;
          case "any.allowOnly":
            err.message = "field1 must be Dummy";
            break; 
          default:
            console.log('validate error type missing', err.type);
            break;
        }
      });
      return errors;
    }),

})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM