簡體   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